Liondancer
Liondancer

Reputation: 16479

Passing state to react-router 1.x

In react-router version 0.13.3 I have

Router.run(routes, createBrowserHistory, function(Handler, state) {
    React.render(<Handler query={ state } path={ state.pathname }/>, document.getElementById('app'))
});

In react-router 1.0.0.rc3 I have

let history = createBrowserHistory();
React.render(<Router history={ history } >{ routes }</Router>, document.getElementById('app'));

With react-router 0.13.3, I was able to pass state to my Components with a callback. I was wondering how I can do the same with version react-router 1.x ?

Upvotes: 3

Views: 325

Answers (1)

Jonny Buchanan
Jonny Buchanan

Reputation: 62813

React Router 1.0 now creates elements from your route components, passing them the following routing-related state as props by default:

  • history - a History object
  • location - a Location object
  • params - parameters extracted from the URL
  • route - the route object the rendered component belongs to
  • routeParams - parameters extracted from the URL for the route object the rendered component belongs to
  • routes - an array of all the route objects which were matched

You should be able to use these to get a hold of routing-related state, e.g. to get the pathname, you could use this.props.location.pathname inside a route component, or pass these onto children which need them.

The 1.0 upgrade guide has more details about this.


If you want to pass additional props to an individual route component when rendering it, you can use React.cloneElement() like so:

{React.cloneElement(this.props.children, {extra: 'extra prop'})

If you want to pass additional props when a route component element is being created, you can pass a custom createElement() function to <Router>.

Upvotes: 3

Related Questions