Sometimes, we want to fix Uncaught TypeError: Cannot read property ‘push’ of undefined with React-Router-Dom.
In this article, we’ll look at how to fix Uncaught TypeError: Cannot read property ‘push’ of undefined with React-Router-Dom.
How to fix Uncaught TypeError: Cannot read property ‘push’ of undefined with React-Router-Dom?
To fix Uncaught TypeError: Cannot read property ‘push’ of undefined with React-Router-Dom, we call the useHistory
hook.
For instance, we write
import { useHistory } from "react-router-dom";
to import the useHistory
hook.
Then we write
const history = useHistory();
to get the history
object from the hook.
Then we use
history.push("/foo");
in a component function to navigate to /foo
.
Conclusion
To fix Uncaught TypeError: Cannot read property ‘push’ of undefined with React-Router-Dom, we call the useHistory
hook.