How can I use history.push('path') in react router 5.1.2 in stateful component?

I had the same issue when using react router v5. When trying to change route programmatically below,

this.props.history.push({
    pathname: `/target-path`,
    state: variable_to_transfer
});

this.props.history was undefined.

Here is my solution for react router v5.

import React, { Component } from "react";
import { withRouter } from 'react-router-dom';

class MyClass extends Component {
    routingFunction = (param) => {
        this.props.history.push({
            pathname: `/target-path`,
            state: param
        });
    }
    ...
}
export default withRouter(MyClass);

Here is reference article. Hope it helps you save your time.


This is how you can navigate to other component using this.props.history.push('/...') in stateful/class based component.

const BasicExample = () => (
  <Router>
    <div>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
      </ul>

      <hr />

      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
    </div>
  </Router>
);
const About = () => (
  <div>
    <h2>About</h2>
  </div>
);
class Home extends React.Component {
  handleClick = e => {
    this.props.history.push("/about");
  };
  render() {
    return (
      <div>
        <h2>Home</h2>

        <button onClick={this.handleClick}>Click to navigate about page</button>
      </div>
    );
  }
}

Live Demo