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();
}
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.
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();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With