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.