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

Sometimes, we want to fix the “Cannot read property ‘push’ of undefined” error with React Router.

In this article, we’ll look at how to fix the “Cannot read property ‘push’ of undefined” error with React Router.

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

To fix the “Cannot read property ‘push’ of undefined” error with React Router, we should call the withRouter component with our route component so the history object is available in the props.

For instance, we write

import { withRouter } from "react-router";

class App extends Component {
  push = () => {
    this.props.history.push("/foo");
  };
  //...
}

export default withRouter(App);

to call withRouter with App so that App has this.props.history.push set.

Now we call this.props.history.push with '/foo' to go to /foo.

Conclusion

To fix the “Cannot read property ‘push’ of undefined” error with React Router, we should call the withRouter component with our route component so the history object is available in the props.