DEV Community

Miriamfark
Miriamfark

Posted on

Nested Dynamic Routes with React Router

One of the futures I really enjoyed using in React Router was the nested routes hook and useParams.

The React Router documentation defines a dynamic segment as :

Dynamic Segment - A segment of a path pattern that is dynamic, meaning it can match any values in the segment. For example the pattern /users/:userId will match URLs like /users/123

In order to use this cool future, we need useParams() which is defined as:

URL Params - The parsed values from the URL that matched a dynamic segment.

This is very helpful for when you have multiple nested routes, such as in an ecommerce store or blog. A parent component shows a list of objects that are links to more information about each product. Without dynamic routing, one would have to manually create a card and route for each product, which is incredibly inefficient especially for stores with many products. This is also a bad idea because as products are added or changed, it requires that the code be updated. Thank goodness for dynamic routing! Keep reading to see how it's done!

  • In App.js I used react-router-dom and to render my route to ComponentDetail.js.

<Route path="locations-detail/:id" element={<ComponentDetail
locations={locations}
passport={passport}
setPassport={setPassport}
bucketList={bucketList}
setBucketList={setBucketList}
/>} />

As you can see, the path=”location-detail/:id”, with id being a dynamic variable.

  • Moving on, with ComponentDetail.js, I imported useParams from react-router-dom and then destructured the useParams object with id as my url variable.

let { id } = useParams();

  • I then used some conditional rendering to render my LocationCard.js, to display the correct location.

if (location.id == id) {
return( <LocationCard
passport={passport}
key={location.id}
id={location.id}
city={location.city}
country={location.country}
location={location}
setPassport={setPassport}
food={location.food}
landmark={location.landmark}
bucketList={bucketList}
setBucketList={setBucketList}
reviews={location.comments}
/>

)

Now, when a user click on location link, the url displays the correct location id and the correct information is displayed on the screen. How cool is that?

Top comments (0)