Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the match when using render in Route component from react router (v4)

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= ?

like image 936
juliangonzalez Avatar asked May 25 '17 20:05

juliangonzalez


People also ask

Which props should you use to match exactly the path you gave for routing?

The exact prop is used to define if there is an exactly the requested path.

Can we use render in route?

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> .


2 Answers

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

like image 153
juliangonzalez Avatar answered Oct 14 '22 05:10

juliangonzalez


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} />
} />
like image 45
Thomas Decaux Avatar answered Oct 14 '22 07:10

Thomas Decaux