Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass props to react-router 4 components?

Id like to use my app entry point as a global state store. Passing info down to children as props.

Using react-router 4, how can I send prop data down to the rendered components. In a similar fashion to this:

<Route Path=“/someplace” component={someComponent} extra-prop-data={dataPassedToSomeComponent} />

I’ve seen some janky workarounds for older versions of react-router, that appear to be deprecated.

What is the correct way of doing this in v4?

like image 316
Vinnie James Avatar asked Dec 13 '25 06:12

Vinnie James


2 Answers

You can pass in a function to the render prop instead of passing in the component directly to the component prop.

<Route path="/someplace" render={() => <SomeComponent props={} />} />

You can read more here.

like image 50
Raj Avatar answered Dec 14 '25 21:12

Raj


And to add to the above answer, if you want the routing properties accessible to the component you need to include those. Now when the router activates "SomeComponent", the component will get all the routing props plus the extra param(s) - in this example "param".

<Route path='/someplace' component={(props) => <SomeComponent param="yo" {...props}/>} />
like image 34
Alan Baer Avatar answered Dec 14 '25 20:12

Alan Baer