Cannot read property 'history' of undefined (useHistory hook of React Router 5)
useHistory won't work in the component where you have your Routes because the context which is needed for useHistory is not yet set.
useHistory will work on any child component or components which you have declared in your Router but it won't work on Router's parent component or Router component itself.
It's because the react-router
context isn't set in that component. Since its the <Router>
component that sets the context you could use useHistory
in a sub-component, but not in that one.
Here is a very basic strategy for solving this issue:
const AppWrapper = () => {
return (
<Router> // Set context
<App /> // Now App has access to context
</Router>
)
}
const App = () => {
let history = useHistory(); // Works!
...
// Render routes in this component
Then just be sure to use the "wrapper" component instead of App
directly.
Note to other people that run into this problem and already have wrapped the component with Router component. Make sure that Router and the useHistory hook are imported from the same package. The same error can be thrown when one of them are imported from react-router and the other one from react-router-dom and the package versions of those packages don't match. Don't use both of them, read about the difference here.