简体   繁体   中英

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?

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 .

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}/>} />

Technically there is 2 ways to do it.

The first one (not the most efficient) is to pass an inline function to the component prop:

<Route 
  path=“/someplace” 
  component={(props) => (
    <SomeComponent {...props} extra-prop-data={ dataPassedToSomeComponent } />
  ) />

The second one is the best solution. To prevent create a new component on every render like on the first exemple, we pass the same inline function but this time to the render prop:

<Route 
  path=“/someplace” 
  render={(props) => (
    <SomeComponent {...props} extra-prop-data={ dataPassedToSomeComponent } />
  ) />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM