Daniel Thompson
Daniel Thompson

Reputation: 2351

React Router - Passing match via props to a component rendered using Route::render

This Route is using the render prop to render a child component with props:

<Route to='/path/:id' render={ () => (<ChildComponent myProp={myProp} match={this.props.match}/>)} />

But the version of match passed seems to be 'matching' against the parent component's route state and is thus not registering id underneath match.route.params.

I figured some solution like this might synchronize the route state:

<Route to='/path/:id' render={ () => (withRouter(<ChildComponent myProp={myProp} />))} />

But that just leads to an error saying that child components cannot be functions...

What's the correct way to deal with this?

Upvotes: 0

Views: 1492

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281744

Since you want to pass the match parameter, you shouldn't pass the one available to parent but the one relevant to the Route. render prop callback receives the Router Props which you can pass down

<Route to='/path/:id' render={(routerProps) => (<ChildComponent {...routerProps} />)} />

or you can simply write

<Route to='/path/:id' component={ChildComponent} />

in which case it will pass on the relevant router props to the component.

and in the child component you can access the match props like

this.props.match.params.id

Upvotes: 4

Related Questions