When declaring a route like this:
App.js
<Route path="/:id" component={RunningProject} />
I can obtain the id param in RunningProject.js like this
constructor(props){
super(props)
console.log(props.match.params.id);
}
But when declaring the route like this
<Route path="/:id" render={() => <RunningProject getProjectById={this.getProject} />} />
I get an error because match no longer get passed into the props.
How can I pass the match object into the props
using render=
instead of component=
?
The exact prop is used to define if there is an exactly the requested path.
There are, however, a few other methods you can use to render something with a <Route> . These are provided mostly for supporting apps that were built with earlier versions of the router before hooks were introduced. You should use only one of these props on a given <Route> .
In order to pass the match object you need to deconstruct the object passed as parameter to the render callback like this:
<Route path="/:id" render={({match}) => <RunningProject getProjectById={this.getProject} match={match} />} />
You can also get the other objects, here's a list of the objects passed:
history
location
staticContext
match
Or you could just pass the whole object, and deconstruct in the recipient component
<Route path="/:id" render={(obj) => <RunningProject getProjectById={this.getProject} obj={obj} />} />
In complement of @juliangonzalez (good) answer:
Better to make your component not "route" aware, so instead of passing React match object you should do:
<Route path="/:id" render={({match}) =>
<RunningProject getProjectById={this.getProject} projectId={match.params.id} />
} />
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