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?
<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} />
)} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With