Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get params in nested routes on react router dom v4?

This is how I have defined my router.

   <Switch>
     {routes.map((route, index) => (
        <Route
          {...this.props}
          path={`/${route}`}
          key={index}
          component={props => (
            <Layout
              {...props}
            />
          )}
        />
      ))}
      <Route component={() => <p>Not Found</p>} />
    <Switch>

I generate a few routes from the routes array and for any route that does not match it goes to the not found.

Inside the Layout component I have further created further routes like this -

   <div className={"Actionbar"}>          
      <Route
        path={`${props.match.url}/:item`}
        component={() => <EditCategory {...props} />}
      />            
    </div>

When I navigate to a nested route, lets say /edibles/icecream, i should be able to see icecream as a param value for property item, right? I don't see it and i can't seem to figure out how to get the id param value in this nested routing use case. My param object looks empty now.

like image 462
Aswin Avatar asked Jan 21 '26 08:01

Aswin


1 Answers

Found the solution. props needs to be passed along with the route. Like this -

<div className={"Actionbar"}>          
  <Route
    path={`${props.match.url}/:item`}
    render={(props) => <EditCategory {...props} />}
  />            
</div>

Missing this doesn't pass the match values

like image 91
Aswin Avatar answered Jan 23 '26 23:01

Aswin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!