Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.props.history is deprecated (react-router)

I was trying to programatically navigate to a different page like so this.props.history.push('/new-path'); it worked, but I got a deprecation warning in console saying:

Warning: [react-router] props.history and context.history are deprecated. Please use context.router. more about it here https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.0.0.md#changes-to-thiscontext


Afterwards I tried to use this new method like so this.context.router.push('/new-path') but this doesn't seem to be the right approach.

like image 811
Ilja Avatar asked Mar 31 '16 10:03

Ilja


People also ask

Is react router deprecated?

This feature has been deprecated because the new structure of Routes is that they should act like components, so you should take advantage of component lifecycle methods instead.

What can I use instead of useHistory?

The useNavigate() hook is introduced in the React Router v6 to replace the useHistory() hook.

What is history in react router?

React Router provides us with a history object, which is accessible by passing this object into each route as a prop. This history object lets us manually control the history of the browser.


1 Answers

Maybe you did forget to define the router as contextType? Assuming you have a component like:

class YourComponent extends React.Component {
      render() {
        return <div></div>;
      }
 }

You have to define the contextTypes as follows right beneath your component:

YourComponent.contextTypes = {
  router: React.PropTypes.object.isRequired
};
like image 89
Richard Rutsche Avatar answered Sep 23 '22 18:09

Richard Rutsche