Sometimes, we may run into the “Uncaught TypeError: Cannot read property ‘push’ of undefined” error when developing apps with React Router.
In this article, we’ll look at how to fix the “Uncaught TypeError: Cannot read property ‘push’ of undefined” error when developing apps with React Router.
Fix the “Uncaught TypeError: Cannot read property ‘push’ of undefined” Error When Developing Apps with React Router
To fix the “Uncaught TypeError: Cannot read property ‘push’ of undefined” error when developing apps with React Router, we can get the history
object from the useHistory
hook.
For instance, we write:
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
NavLink,
useHistory
} from "react-router-dom";
const Foo = () => {
return <p>foo</p>;
};
const Bar = () => {
const history = useHistory();
return (
<>
<p>bar</p>
<p onClick={() => history.push("/foo")}>foo</p>
</>
);
};
export default function App() {
return (
<Router>
<div>
<ul>
<li>
<NavLink to="/foo">foo</NavLink>
</li>
<li>
<NavLink to="/bar">bar</NavLink>
</li>
</ul>
<Switch>
<Route path="/foo" children={<Foo />} />
<Route path="/bar" children={<Bar />} />
</Switch>
</div>
</Router>
);
}
In the Bar
component, we call useHistory
to return the history object and assign it to history
.
Then we call history.push
in the function we set as the value of the onClick
prop to go to the /foo
page.
We can only call this inside route components and their children.
Otherwise, we’ll get the “Uncaught TypeError: Cannot read property ‘push’ of undefined” again.
Conclusion
To fix the “Uncaught TypeError: Cannot read property ‘push’ of undefined” error when developing apps with React Router, we can get the history
object from the useHistory
hook.
We can only call this inside route components and their children.