Thursday, June 5, 2025

Dynamic Route in React Router With Example

In this post we'll see what are dynamic routes in React.

When you configure a route like this-

<Route path="about" element={<About />} />

That is considered a static route which matches the /about path segment as it is.

Now, consider a scenario where you want to create a dynamic path where part of the URL is dynamic, which may change. For example, if you have a product page that shows product names and clicking on any product displays the details of that product. This means you need to pass id of the clicked product so that you can get details for that particular product.

In this case you can add the id part as dynamic path segment so that any path in this format /product/{ID} is mapped to the same route.

How to create dynamic route in React

In a route, if a path segment starts with : then it becomes a "dynamic segment".

<Route path="product/:productId" element={<ProductDetail />} />

Here :productid is the dynamic part and it will match any URL like- product/2, product/15 and so on.

You can have multiple dynamic segments in one route path:

<Route
  path="/category/:categoryId/product/:productId"
  element={<ProductDetail />}
/>

How to retrieve route parameters

When the route matches the URL, the dynamic segment with in the URL will be parsed and provided as params to other router APIs like useParams.

useParams() hook in react-router can be used to get values of dynamic segments in route path. This hook returns an object of key/value pairs of the dynamic params from the current URL that were matched by the routes.

For example, if /product/15 matches the route path /product/:productId then useParams() hook will return an object as { productId:15}

const params = useParams();

will assign this object to params.

Then you can get the specific route parameter like this-

params.productId

Or you can use object destructuring to get the productid param from the object returned by useParams() hook.

let { productid } = useParams();

React example - Dynamic routing

In this example there will be a Product page displaying the available product names and a ProductDetail page that shows details for the selected product. ProductId is passed as dynamic path segment.

Route Configuration

App.js

import { BrowserRouter, Route, Routes } from 'react-router';
import About from './components/routes/About';
import Home from './components/routes/Home';
import NavigationNavLink from './components/routes/NavigationNavLink';
import RouteProduct from './components/routes/RouteProduct';
import RouteProductDetails from './components/routes/RouteProductDetails';

function App() {
  return (
    <>
      <BrowserRouter >

        <Routes>
          <Route path="/" element={<NavigationNavLink />}>
            <Route index element={<Home />} />
            <Route path="product" element={<RouteProduct />}> 
              <Route path=":productId" element={<RouteProductDetails />} /> 
            </Route>
            <Route path="about" element={<About />} />
          </Route>
        </Routes>
      </BrowserRouter>
    </>
  );
}

export default App;

Navigation Menu

src\components\routes\NavigationNavLink.js

import { NavLink, Outlet } from "react-router";
import "./navigation.css";
const NavigationNavLink = () => {
    const style = (({ isActive, isPending }) => 
        isPending ? "pending" : isActive ? "active" : ""
    );
    return(
        <>
            <nav id="menu" className="navbar navbar-expand-lg bg-dark navbar-dark">
                <div className="container-fluid">
                    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarMenu" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                        <span className="navbar-toggler-icon"></span>
                    </button>

                    <div className="collapse navbar-collapse" id="navbarMenu">
                        <ul className="navbar-nav">
                            <li>
                                <NavLink className={style} to="/">
                                    Home
                                </NavLink>
                            </li>
                            <li>
                                <NavLink className={style} to="/product">
                                    Product
                                </NavLink>
                            </li>
                            <li>
                                <NavLink className={style} to="/about">
                                    About
                                </NavLink>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <Outlet />
        </>
    );
}

export default NavigationNavLink;

CSS styling

src\components\routes\navigation.css

#menu a:link,
#menu a:visited {
    color: gray;
}
#menu a:hover {
    color: white;
}
#menu a.active {
    color: #7FFFD4;
}

#menu a {
    text-decoration: none;
}

#menu ul {
    gap: 1rem;
}

Components

src\components\routes\Home.js

const Home = () => {
    return (
    <>
        <h2>This is home page</h2>
    </>
    )

}

export default Home;

src\components\routes\About.js

const About = () => {
    return <h2>This is about page</h2>
}

export default About;

src\components\routes\RouteProduct.js

Uses Bootstrap 5 styling.

import { Link, Outlet } from "react-router";

export const DUMMY_PRODUCTS = [
    {id:1, name:'Laptop', price:455.50},
    {id:2, name:'Mouse', price:15.89},
    {id:3, name:'USB', price:10.00},
    {id:4, name:'HDD', price:55.50}
];

const RouteProduct = () => {

    return(
        <>
        <div className= "row">
            <div className="col-sm-4">
                <h2>Products</h2>
 
                <ul className="list-group">

                    {DUMMY_PRODUCTS.map(product =><li className="list-group-item" key={product.id}> 
                        <Link to={`/product/${product.id}`}>{product.name}</Link></li>
                    )}
                </ul>

            </div>
            <div className="col-sm-4">
                <Outlet />
            </div>
        </div>
        </>
    )
}

export default RouteProduct;

Some of the points to note here-

  1. An array of product objects (hardcoded) is initialized with 3 properties- id, name, price.
  2. While iterating through the array, with each name a link is created to pass /product/{id} as path.

src\components\routes\RouteProductDetails.js

import { useParams } from "react-router"
import { DUMMY_PRODUCTS } from "./RouteProduct";

const RouteProductDetails = () => {
    const params = useParams();
    const product = DUMMY_PRODUCTS.find(product => product.id === +params.productId);
    return (
        <>
            <h2>Product Details</h2>
            <div className="row">
                <div className="col-xs-6">
                    <span>Name: </span>{product.name}
                </div>
            </div>
            <div className="row">
                <div className="col-xs-6">
                    <span>Price: </span>{product.price}
                </div>

            </div>
        </>
    )
}

export default RouteProductDetails;

Some of the important points here-

  1. Using useParams() hook, values of the dynamic path segment is retrieved.
  2. Find method of the Array is used to find the product that matches the passed Id.

When menu option Product is clicked.

Dynamic Route in React

Clicking on one of the products-

Dynamic Route in React router

That's all for this topic Dynamic Route in React Router With Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Routing in React With Example
  2. Link in React Router With Example

You may also like-

  1. React Declarative Approach
  2. React Virtual DOM
  3. React create-react-app Project Structure
  4. JavaScript Rest Parameter
  5. ArrayList in Java With Examples
  6. Count Number of Times Each Character Appears in a String Java Program
  7. Java Stream API Interview Questions And Answers
  8. What is Client Side Routing in Angular

No comments:

Post a Comment