React-router: Allow passing props to <Route> to be passed down to the component it renders

Created on 14 Sep 2017  路  3Comments  路  Source: ReactTraining/react-router

The concept

Allow passing props to Route to be passed to the component it renders. For example:

<Route path="/foo" component={MyComponent} foo="bar" />

In that case, if the route matched, MyComponent would be rendered as follows:

<MyComponent match={...} history={...} foo="bar" />

Or, if you don't like Route accepting arbitrary properties, maybe we can achieve the same with something like:

<Route path="/foo" component={MyComponent} extraProps={{foo: "bar"}} />

Use case

Sometimes, I have a component that I want to render in a Route, but make it reusable in such a way that it doesn't have to know about the URL structure that it is in. For example, consider a Twitter clone's UserProfile component:

// Somewhere in the app:
<Route path="/users/:userId" component={UserProfile} />

let UserProfile = ({match}) => {
  return <div>
    {/* ... user profile stuff ... */}
    <Route path={match.path + "/followers"} component={UserFollowers} />
  </div>
}

The UserFollowers component needs access to the userId of the user to show their followers, and it can get that from match.params, but what if we also have some kind of dashboard that displays the currently logged-in user's followers?

// Somewhere in the app:
<Route path="/dashboard/" component={Dashboard} />

let Dashboard = ({match}) => {
 // ... Somehow obtain the userId
  return <div>
    {/* ... dashboard stuff ... */}
    <Route path={match.path + "/followers"} component={UserFollowers} />
  </div>
}

In order to pass the userId variable to UserFollowers, I'd need to use render, and create a whole new function, just to pass the prop to my component. Or, I'd have to use a HOC like recompose's withProps. Both of these options work, but I think it'd be more elegant to just have a way to pass props through via Route.

Most helpful comment

This has been discussed many, many, many, many times.

The simplest solution is just to use render instead:

<Route path="/abc" render={()=><TestWidget num="2" someProp={100}/>}/>

All 3 comments

This has been discussed many, many, many, many times.

The simplest solution is just to use render instead:

<Route path="/abc" render={()=><TestWidget num="2" someProp={100}/>}/>

<Route path="/abc" render={(props) => <TestWidget {...props} someProp={100} />} />
is more complete as it forwards the default props as well (e.g: match prop).

just to confirm that it works for me also ;)
<Route exact path='/orders-confirmed-list' render={(props) => <Orders {...props} status={'CONFIRMED'} />} />

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ArthurRougier picture ArthurRougier  路  3Comments

winkler1 picture winkler1  路  3Comments

sarbbottam picture sarbbottam  路  3Comments

davetgreen picture davetgreen  路  3Comments

stnwk picture stnwk  路  3Comments