Categories
React Answers

How to fix the “Cannot read property ‘history’ of undefined” error React Router 5?

Spread the love

Sometimes, we want to fix the "Cannot read property ‘history’ of undefined" error React Router 5.

In this article, we’ll look at how to fix the "Cannot read property ‘history’ of undefined" error React Router 5.

How to fix the "Cannot read property ‘history’ of undefined" error React Router 5?

To fix the "Cannot read property ‘history’ of undefined" error React Router 5, we should wrap our route components inside Router.

Then we can call useHistory in the components to return the history object.

For instance, we write

const AppWrapper = () => {
  return (
    <Router>
      <App />
    </Router>
  );
};

to add the AppWrapper component that wraps Router in App.

Then in App, we write

const App = () => {
  const history = useHistory();
  //...
};

to call useHistory to return the history object.

Conclusion

To fix the "Cannot read property ‘history’ of undefined" error React Router 5, we should wrap our route components inside Router.

Then we can call useHistory in the components to return the history object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *