Categories
React Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *