Categories
React Answers

How to use history.push(‘path’) in react router 5.1.2 in a React stateful component?

Spread the love

To use history.push(‘path’) in react router 5.1.2 in a React stateful component, we call withRouter with our component so that the history prop is available in our component.

For instance, we write

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);

to create the routingFunction method that calls this.props.history.push with an object that redirects to pathname.

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 *