In some cases, we may need to pass the real-time data to an API and in such a case static routes won’t work and we need to create a dynamic route based on the data.

In this article, we will see how to create a dynamic route in react using the react-router-dom.

We can create dynamic routes in React using the React Router’s Route params. Using the route parameters we can define a placeholder within the route and can match the dynamic part of the URL. These dynamic parts from the URL can be fetched and processed.

Following is how we can create a dynamic route in React

Define a dynamic route path using a parameter placeholder as shown below.

<Route path="/users/:id" component={UserDetails} />

Now, using the useParams hook, access the route parameter within the component.

import { useParams } from 'react-router-dom';

const UserDetails = () => {
  const { id } = useParams();
  
  // id contains the dynamic data which is passed with route

};

Categorized in:

Tagged in: