Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using React Router withRouter

How do you get the routing context, location, params, etc, when using withRouter()?

import { withRouter } from 'react-router';

const SomeComponent = ({location, route, params}) => (
    <h1>The current location is {location.pathname}</h1>
);

const ComposedWithRouter = withRouter(SomeComponent);

Can you obtain that info using withRouter or do these things have to be explicitly passed down the component tree?

like image 891
Tabbyofjudah Avatar asked Aug 26 '16 21:08

Tabbyofjudah


2 Answers

So, no using context anymore. It's all available in the props:

SomeComponent.propTypes = {
  location: React.PropTypes.shape({
    pathname: React.PropTypes.string,
    query: React.PropTypes.shape({
      ...
    })
  }),
  params: React.PropTypes.shape({
    ...
  }),
  router: React.PropTypes.object
}

const ComposedWithRouter = withRouter(SomeComponent);

So then lets say in SomeComponent you wanted to send the user to a new route, you simply do this.props.router.push('someRoute')

like image 170
Matthew Herbst Avatar answered Oct 27 '22 13:10

Matthew Herbst


Getting location etc. via withRouter was added in react-router version 2.7. Dan Abramov recommends upgrading to 3.0 to use withRouter. Before 2.7, it only provided a set of functions.

like image 41
stone Avatar answered Oct 27 '22 12:10

stone