How to fix this.props.history.push() not working with React Router v4?

Sometimes, we want to fix this.props.history.push() not working with React Router v4.

In this article, we’ll look at how to fix this.props.history.push() not working with React Router v4.

How to fix this.props.history.push() not working with React Router v4?

To fix this.props.history.push() not working with React Router v4, we should we call withRouter with the component we’re calling this.props.history.push on to make the method available.

For instance, we write

import React, { Component } from "react";
import { withRouter } from "react-router";
// you can also import "withRouter" from 'react-router-dom';

class Example extends Component {
  render() {
    const { match, location, history } = this.props;
    return (
      <div>
        <div>You are now at {location.pathname}</div>
        <button onClick={() => history.push("/")}>{"Home"}</button>
      </div>
    );
  }
}

export default withRouter(Example);

to call withRouter with Example so that history is added to this.props.

We should also make sure Example is set as a component that’s rendered with Route‘s render prop.

Conclusion

To fix this.props.history.push() not working with React Router v4, we should we call withRouter with the component we’re calling this.props.history.push on to make the method available.