Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Props to React-Router 4.0.0 Children Routes

I'm trying to migrate an existing react-router 3.0.0 app to 4.0.0. Within the router, I need pass an additional non routing-related prop to its children.

There are a few somewhat hacky ways to accomplish this in previous versions of react-router, detailed in this post. My personal favorite was this method using cloneElement, since it ensured that all of the react-router props were copied over as well:

// react-router 3.0.0 index.js JSX
<Router history={browserHistory}
  <Route path="/" component={App}>
    <Route path="/user/:userId" component={User} />
    <IndexRoute component={Home} />
  </Route>
</Routes>

// App component JSX (uses cloneElement to add a prop)
<div className="App">
  { cloneElement(props.children, { appState: value }) }
</div>

So far my new App component looks like:

// react-router 4.0.0 App component JSX (moved routing code out of index.js and into here)
<BrowserRouter>
  <div className="App">
    <Match exactly pattern="/" component={Home} />
    <Match pattern="/user/:userId" component={User} />
    <Miss component={Home} />
  </div>
</BrowserRouter>

What's the best way to add the appState prop to each of the Match's components while retaining the provided router props?

like image 305
dougmacklin Avatar asked Dec 06 '16 21:12

dougmacklin


1 Answers

<Route> can take a render prop instead of a component. This allows you to inline the component definition.

<Route path='/user/:userId' render={(props) => (
  <User appState={value} {...props} />
)} />
like image 161
Paul S Avatar answered Oct 12 '22 05:10

Paul S