How to Retrieve Data from a Dynamic Route in React Router
When using React Router with dynamic parameters, it is common to need to fetch the data required to display on the page. In this blog, we will explore two ways to achieve this.
Using useParams Hook
To begin, declare the route in the following manner:
1 | <Route path="/project/:id"> |
In this code snippet, the :id
in the path represents the dynamic part of the URL, which will be accessible as the id
parameter in the SingleProject
component.
Next, in the SingleProject
component, use the useParams
hook from the react-router-dom
package to access the id
parameter:
1 | import { useParams } from 'react-router-dom'; |
In this way, you can utilize the id
parameter to filter data from an array or query a database.
Using Props
An alternative approach is to pass the props
to the component using the render
prop of the Route
component. Here’s how you can achieve it:
1 | <Route path="/project/:id" render={(props) => <SingleProject {...props} />} /> |
Inside the SingleProject
component, which is responsible for displaying the data, access the parameters by destructuring match.params
from the props
object:
1 | const SingleProject = (props) => { |
This approach is useful when you want to lookup data in your data source before rendering the component.
In some cases, you may need to obtain the parameters directly in the inline rendered routes. Here’s an example:
1 | const posts = [ |
In this case, the id
parameter is used to lookup post data from the data source before rendering the Post
component.
tags: [“React Router”, “dynamic route”, “data fetching”, “useParams”, “react-router-dom”]