Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I found this, but it is a solution for a stateless component.

import { useHistory } from "react-router-dom";

function App() {
  let history = useHistory();
}
like image 550
Adam Gajdečka Avatar asked Dec 19 '19 02:12

Adam Gajdečka


People also ask

How do I get past path in react router?

To detect previous path in React Router, we can set the state property to an object with the location. pathname as the value. <Link to={{ pathname: "/nextpath", state: { prevPath: location.

How do you push to history in react router v4?

To push to History in React Router v4, we can use the createBrowserHistory method to return the history object. Then we can call push on the history object. import { createBrowserHistory } from 'history'; export default createBrowserHistory();


1 Answers

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.

Update for Next.js
You should use withRouter from 'next/router' in Next.js.

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

class MyClass extends Component {
  routingFunction = (param) => {
     this.props.router.push('/dashboard');
  }
  ...
}
export default withRouter(MyClass);
like image 198
Bi Wu Avatar answered Sep 25 '22 12:09

Bi Wu