#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Routing and Navigation

Dynamic Routes with Params

Dynamic routes let a single route definition handle many URLs, such as /products/1, /products/2 and /products/sofa-blue. In React Router you mark part of the path with a colon, like /products/:productId, and the component reads the actual value from the URL with the useParams hook. This is how detail pages for products, posts and user profiles are built.

Declaring a route parameter

A segment that starts with a colon is a placeholder. React Router matches any value in that position and stores it under the name you gave it. You can have more than one, for example /courses/:courseId/lessons/:lessonId.

import { BrowserRouter, Routes, Route, Link, useParams } from "react-router-dom";

const products = [
  { id: "p1", name: "Desk lamp" },
  { id: "p2", name: "Notebook" },
];

function ProductList() {
  return (
    <ul>
      {products.map((p) => (
        <li key={p.id}>
          <Link to={`/products/${p.id}`}>{p.name}</Link>
        </li>
      ))}
    </ul>
  );
}

function ProductDetail() {
  const { productId } = useParams();
  const product = products.find((p) => p.id === productId);

  if (!product) return <p>No product found for "{productId}".</p>;
  return <h2>{product.name}</h2>;
}

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/products" element={<ProductList />} />
        <Route path="/products/:productId" element={<ProductDetail />} />
      </Routes>
    </BrowserRouter>
  );
}

Reading and using the parameter

useParams returns an object whose keys match the names in the path. Destructure the one you need and use it to find data locally or to fetch it from an API. When fetching, put the parameter in the dependency array of useEffect, so the component loads new data when the user moves from one product to another.

The parameter is always a string

The most common bug with params is a type mismatch. If your data uses numeric IDs, products.find((p) => p.id === productId) never matches, because productId is the string "1" while p.id is the number 1. Convert with Number(productId), or compare as strings. Since the value comes from the address bar, also handle values that do not exist or are malformed, as the "No product found" message does.

Same component, new parameter

When you navigate from /products/p1 to /products/p2, React Router keeps the same ProductDetail component mounted and only changes the parameter. Any state you set up once, such as form fields initialised from the product, will not reset by itself. Effects that depend on productId will rerun, which is why the dependency array matters. If you truly want a fresh component per item, give it a key based on the parameter.

Building links to dynamic routes

Generate the URL with a template literal, as in to={`/products/${p.id}`}. For slugs that might contain spaces or special characters, wrap the value in encodeURIComponent so the link stays valid. In code, use the useNavigate hook to move to a dynamic route after an action, for example navigate(`/orders/${newOrder.id}`) once an order is created.

Params versus query strings

Use route params for the identity of the thing being shown, the part without which the page makes no sense. Use query strings, read with useSearchParams, for optional settings like sorting, filters or the current page, such as /products?sort=price.

A route can also make a parameter optional by adding a question mark, as in /blog/:category?, so the same page serves both the full list and a filtered one. Use this sparingly, since separate routes are often clearer.

Takeaway: mark variable segments with a colon, read them with useParams, convert them from strings before comparing, handle missing items, and include the param in effect dependencies.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course