DEV Community

Cover image for Dynamic Routes in React
Shubham Tiwari
Shubham Tiwari

Posted on

Dynamic Routes in React

Hello Everyone today i will be discussing about Dynamic Routes in React JS.I will be using react-router-dom library as it is easy to use and flexible and can be used for both client and server side routings

Let's get started...

Setting the Routing Part -


import { BrowserRouter as Router } from 'react-router-dom'
      <App />
Enter fullscreen mode Exit fullscreen mode
  • In your index.js file ,Import the Router component and wrap the App component inside Router component.

Creating the Routes -


import React from 'react';
import { Routes, Route, Link } from 'react-router-dom';
import UserDetails from './UserDetails';
import './App.css';

function App() {
  const users = [1,2,3,4,5,6,7,8,9,10];
  return (
    <div className="">
      <div className="mx-20 flex gap-5 my-24">
 => {
            return (
              <Link to={`users/${user}`}>User {user}</Link>
        <Route path="users/:userId" element={<UserDetails />} />


export default App;
Enter fullscreen mode Exit fullscreen mode
  • First we have imported the Routes, Route and Link from react-router-dom.
  • Routes is used to wrap all the Route component inside it.
  • Route is used to specify which component will be rendered at a particular path or url, path is provided using "path" attribute and component is provided using "element" attribute.
  • Link is used to redirect the user to the path provided in the link using "to" attibute.We made the Link dynamic using template string and map the values of user array to the Link componenet with 1-10 number.
  • In the Route component "path" attribute , we have used "users/:userId" , ":" colon is used to make the route dynamic and the parameters can be accessed using the name "userId" as provided in the route path after colon.

Creating the Dynamic component -


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

function UserDetails() {
    const {userId} = useParams();
  return (
        <h1 className="text-indigo-600 m-12">User {userId}</h1>

export default UserDetails
Enter fullscreen mode Exit fullscreen mode
  • We have used useParam hook to access the parameter values from the url.
  • as you can see we have used the exact same value "userId" for accessing the value.
  • You can check in the output, when you click on any link , the text in the UserDetail component will be changed.


You can contact me on -
Instagram -
LinkedIn -
Email -

^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> <--

Also check these posts as well

Top comments (1)

andreisibisan profile image
Andrei Sibisan

for me it was the best tutorial on the topic. Concise and insightful. Thank you!