11

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?

2 Answers 2

14

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

Sign up to request clarification or add additional context in comments.

2 Comments

So the only solution is to explicitly pass props to child components? What if you wanted to make and distribute a <BreadCrumbs /> component?
Well, that depends on how tied in with the router you wanted it to be. If say you only cared about distributing it to people using react-router, then instead of actually exporting BreadCrumbs, you would export withRouter(BreadCrumbs)` and that way it would always have access to the router/location.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.