Pass id as props in react-router-dom

Cohchi picture Cohchi · Aug 16, 2018 · Viewed 9.6k times · Source

I would like to pass an ID in props to a component react I use react-router-dom Here is my app.js file

          <Switch location={this.props.location}>
        <Route exact path="/" component={Home} />
        <Route path="/list" component={List} />
        <Route path='/img/:imgId' component={() => <Img imgId={this.props.params.imgId}/>} />
      </Switch>

When I go to the next url img / 2, the router sends me the right page, but the id is not present in the props. When I look into react developer tools on chrome, I can see that

<Switch>
 <Route>
  <component>
   <Img>
   </Img>
  </component>
 </Route>
</Switch>

In the component called component, I have something in props.match.params.imgId But when I go on the Img component, here is what I have as props: imgId: {empty object}

Do you know how to recover the id in parameter?

Thanks :)

Answer

Jo&#227;o Cunha picture João Cunha · Aug 16, 2018

You should do it like this:

1st: change your Route declaration

<Switch location={this.props.location}>
  <Route exact path="/" component={Home} />
  <Route path="/list" component={List} />
  <Route path='/img/:imgId' component={Img} />
</Switch>

2nd: you should access the prop from match injected by react-router like in this example

const Img = ({ match }) => (
  <div>
    <h3>IMAGE ID: {match.params.imgId}</h3>
  </div>
);

but of course you can easily adapt that code into your own.