Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass id as props in react-router-dom

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 :)

like image 283
Cohchi Avatar asked Aug 16 '18 16:08

Cohchi


Video Answer


2 Answers

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.

like image 187
João Cunha Avatar answered Oct 08 '22 03:10

João Cunha


You would use the functional callback pattern in case where you want to pass some props other than router props to the component. In your case you can simply render the Img component

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

and access the imgId in Img component like this.props.match.params.id.

However to point out the problem in your current code, it doesn't work correctly because you are trying to pass the parents match props to the Img component whereas you need to pass the Route's own props like

<Switch location={this.props.location}>
    <Route exact path="/" component={Home} />
    <Route path="/list" component={List} />
    <Route path='/img/:imgId' component={(routerProps) => <Img imgId={routerProps.match.params.imgId}/>} />
</Switch>
like image 3
Shubham Khatri Avatar answered Oct 08 '22 03:10

Shubham Khatri