Popular Searches
Popular Course Categories
Popular Courses

Dynamic Route Parameters

Dynamic Route Parameters

React Router

Dynamic Route Parameters in React Router

Dynamic Route Parameters allow React applications to display different content based on values included in the URL. They are useful for product details, user profiles, blog posts, course details, student records, and other data-driven pages.

For example, instead of creating separate routes for every product, you can define one route such as /products/:productId and use the product ID from the URL to display the relevant product.

Course: React JS Training | JustAcademy React JS Training


1. What Are Dynamic Route Parameters?

Dynamic route parameters are variable values captured from a URL by a route pattern. In React Router, a dynamic path segment begins with a colon (:) followed by a parameter name.

Example

<Route path="/products/:productId" element={<ProductDetails />} />

In this example:

  • /products/101 matches the route with productId equal to "101".
  • /products/202 matches the same route with productId equal to "202".
  • :productId is the dynamic parameter name.
  • ProductDetails is the component rendered for the matching route.

2. Why Do We Use Dynamic Route Parameters?

  • Product pages: Display different products using their IDs or slugs.
  • User profiles: Show profile information for a particular user.
  • Blog applications: Display individual articles using post IDs or slugs.
  • Course websites: Show details for a selected course.
  • Student portals: Display student records using student IDs.
  • Reusable components: Use one component for many URLs instead of creating separate components for every record.

3. Prerequisites

Before working with dynamic route parameters, you should understand:

  • React components and JSX.
  • JavaScript variables and objects.
  • React Router's BrowserRouter.
  • The Routes and Route components.
  • The Link component for navigation.

4. Install React Router

If React Router is not already installed in your project, install it using npm.

npm install react-router

The examples in these notes use the current declarative React Router imports from react-router. Existing projects and older tutorials may use react-router-dom, depending on their installed version and setup.

5. Set Up BrowserRouter

Wrap your application with BrowserRouter so that route definitions and navigation components can access the router context.

import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router";
import App from "./App";

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

6. Creating Your First Dynamic Route

Let's create a simple product details page that displays a product ID from the URL.

App.jsx

import { Routes, Route } from "react-router";
import ProductDetails from "./ProductDetails";

function App() {
  return (
    <Routes>
      <Route
        path="/products/:productId"
        element={<ProductDetails />}
      />
    </Routes>
  );
}

export default App;

ProductDetails.jsx

import { useParams } from "react-router";

function ProductDetails() {
  const { productId } = useParams();

  return (
    <div>
      <h1>Product Details</h1>
      <p>Product ID: {productId}</p>
    </div>
  );
}

export default ProductDetails;

How It Works

  1. The user opens a URL such as /products/101.
  2. React Router matches it against /products/:productId.
  3. The useParams() hook reads the matched route parameters.
  4. The productId variable receives the string "101".
  5. The component displays the product ID.

7. Understanding the useParams Hook

useParams() is a React Router hook that returns an object containing the dynamic parameters matched by the current route. You can use it inside a component rendered within the appropriate router context.

Example

import { useParams } from "react-router";

function UserProfile() {
  const params = useParams();

  return (
    <div>
      <h2>User Profile</h2>
      <p>User ID: {params.userId}</p>
    </div>
  );
}

export default UserProfile;

For a route such as /users/45 matched by /users/:userId, the value of params.userId is "45".

Important Points

  • useParams() returns an object of parameter names and values.
  • Parameter names must match the names defined in the route path.
  • Parameter values are strings, so convert them when numeric calculations are required.
  • Child routes inherit parameters from their parent routes.

8. Using Multiple Dynamic Parameters

A single route can contain more than one dynamic parameter. This is useful when a page depends on multiple pieces of information.

Route Definition

<Route
  path="/categories/:categoryId/products/:productId"
  element={<ProductDetails />}
/>

Component

import { useParams } from "react-router";

function ProductDetails() {
  const { categoryId, productId } = useParams();

  return (
    <div>
      <h2>Product Details</h2>
      <p>Category ID: {categoryId}</p>
      <p>Product ID: {productId}</p>
    </div>
  );
}

export default ProductDetails;

For the URL /categories/5/products/101, the parameters are:

  • categoryId = "5"
  • productId = "101"

9. Navigating to Dynamic Routes with Link

The Link component lets users navigate to URLs that contain dynamic values.

import { Link } from "react-router";

function ProductList() {
  return (
    <div>
      <h2>Product List</h2>
      <ul>
        <li>
          <Link to="/products/101">View Laptop</Link>
        </li>
        <li>
          <Link to="/products/102">View Smartphone</Link>
        </li>
        <li>
          <Link to="/products/103">View Headphones</Link>
        </li>
      </ul>
    </div>
  );
}

export default ProductList;

Each link navigates to the same dynamic route pattern but supplies a different product ID.

10. Complete Example: Product Listing and Details

This example combines a product list, dynamic route parameters, and a product details component.

App.jsx

import { Routes, Route } from "react-router";
import ProductList from "./ProductList";
import ProductDetails from "./ProductDetails";

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

export default App;

ProductList.jsx

import { Link } from "react-router";

const products = [
  { id: 101, name: "Laptop" },
  { id: 102, name: "Smartphone" },
  { id: 103, name: "Headphones" }
];

function ProductList() {
  return (
    <div>
      <h1>Products</h1>
      {products.map((product) => (
        <p key={product.id}>
          <Link to={`/products/${product.id}`}>
            {product.name}
          </Link>
        </p>
      ))}
    </div>
  );
}

export default ProductList;

ProductDetails.jsx

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

const products = {
  101: { name: "Laptop", price: 55000 },
  102: { name: "Smartphone", price: 25000 },
  103: { name: "Headphones", price: 3000 }
};

function ProductDetails() {
  const { productId } = useParams();
  const product = products[productId];

  if (!product) {
    return (
      <div>
        <h2>Product Not Found</h2>
        <Link to="/products">Back to Products</Link>
      </div>
    );
  }

  return (
    <div>
      <h1>{product.name}</h1>
      <p>Product ID: {productId}</p>
      <p>Price: ₹{product.price}</p>
      <Link to="/products">Back to Products</Link>
    </div>
  );
}

export default ProductDetails;

Note: This example uses a small local object as sample data. In a real application, you would usually retrieve product details from an API or database using the route parameter.

11. Dynamic Parameters vs. Query Parameters

Dynamic route parameters and query parameters both carry information in a URL, but they serve different purposes.

Feature Dynamic Route Parameter Query Parameter
Example URL /products/101 /products?category=electronics
Typical use Identifies a particular resource. Filters, sorts, searches, or modifies a view.
Defined in Route path, such as /products/:productId. URL query string after ?.
Access method useParams() useSearchParams()
Example value productId = "101" category = "electronics"

Example of Reading Query Parameters

import { useSearchParams } from "react-router";

function ProductSearch() {
  const [searchParams] = useSearchParams();
  const category = searchParams.get("category");

  return <p>Selected category: {category}</p>;
}

export default ProductSearch;

12. Optional Route Parameters

React Router supports optional route segments by placing a question mark (?) after a segment. This can be useful when a URL segment may or may not be provided.

<Route
  path="/:lang?/products"
  element={<ProductList />}
/>

This route can match both /products and /en/products. In the second URL, the lang parameter is "en".

Use optional segments only when they make the URL structure clearer and are supported by the React Router version used in your project.

13. Catch-All Route Parameters

A route ending in /* can match the remaining portion of a URL, including additional path segments. This is useful for file paths or nested paths of unknown length.

<Route path="/files/*" element={<FileViewer />} />
import { useParams } from "react-router";

function FileViewer() {
  const params = useParams();
  const filePath = params["*"];

  return <p>Requested file path: {filePath}</p>;
}

export default FileViewer;

For the URL /files/documents/notes.pdf, the catch-all parameter contains "documents/notes.pdf".

14. Converting Route Parameters to Numbers

Route parameters are returned as strings. If a parameter represents a numeric ID or is used for mathematical calculations, convert it to a number and validate it.

import { useParams } from "react-router";

function StudentDetails() {
  const { studentId } = useParams();
  const id = Number(studentId);

  if (!Number.isInteger(id) || id <= 0) {
    return <h2>Invalid Student ID</h2>;
  }

  return <h2>Student ID: {id}</h2>;
}

export default StudentDetails;

Validation helps prevent unexpected values from being treated as valid numeric identifiers. For real data, also check whether the requested record exists and whether the current user is authorized to access it.

15. Common Mistakes and Solutions

Mistake Cause Solution
Parameter value is undefined The parameter name in the component does not match the route path. Ensure the names match, for example :productId and productId.
useParams does not work The component is not rendered within the matching router context. Check BrowserRouter and the route configuration.
Wrong product appears The parameter is used incorrectly to look up the record. Verify the lookup key and data structure.
Numeric comparison fails The parameter is a string but the code expects a number. Convert and validate it when appropriate.
Unknown ID causes an error The requested record does not exist. Display a not-found message and handle missing data.
Direct URL refresh returns 404 The production server is not configured for client-side routes. Configure the server's SPA fallback appropriately.

16. Best Practices

  • Use meaningful parameter names such as :userId, :productId, or :postId.
  • Use useParams() to read dynamic route values inside matching route components.
  • Validate parameter values before using them in data lookups.
  • Handle missing or invalid records gracefully.
  • Use query parameters for filtering, sorting, and search criteria.
  • Avoid repeating route definitions for every individual record.
  • Use a data source or API for real-world records instead of relying on hard-coded objects.
  • Check authentication and authorization on the server when retrieving protected data; a URL parameter is not proof of permission.
  • Test valid, invalid, and missing parameter values.

17. Practical Project: Student Details Application

Objective: Build a student portal where each student has a unique URL.

Project Requirements

  1. Create a React project and install React Router.
  2. Wrap the application in BrowserRouter.
  3. Create a student list component.
  4. Define a dynamic route such as /students/:studentId.
  5. Use Link to navigate to each student's details page.
  6. Use useParams() to read the student ID.
  7. Display the student's name and course from sample data or an API.
  8. Handle invalid student IDs with a friendly message.
  9. Test the application with different student IDs.

Sample Route Configuration

import { Routes, Route } from "react-router";
import StudentList from "./StudentList";
import StudentDetails from "./StudentDetails";

function App() {
  return (
    <Routes>
      <Route path="/students" element={<StudentList />} />
      <Route
        path="/students/:studentId"
        element={<StudentDetails />}
      />
    </Routes>
  );
}

export default App;

18. Interview Questions and Answers

Q1. What are dynamic route parameters?

Answer: They are variable URL segments defined in a route path, such as :productId, that allow a route to handle different values.

Q2. How do you define a dynamic route in React Router?

Answer: Use a colon followed by the parameter name, such as <Route path="/users/:userId" element={<UserProfile />} />.

Q3. What is the purpose of useParams?

Answer: The useParams() hook returns an object containing the dynamic parameters matched by the current route.

Q4. Can a route have multiple parameters?

Answer: Yes. For example, /categories/:categoryId/products/:productId contains two dynamic parameters.

Q5. Are route parameter values strings or numbers?

Answer: They are strings. Convert them when numeric values are needed.

Q6. What is the difference between route parameters and query parameters?

Answer: Route parameters are part of the path, such as /products/101. Query parameters follow ?, such as /products?category=books.

Q7. How do you handle an invalid dynamic parameter?

Answer: Validate the value, check whether the requested record exists, and render an appropriate error or not-found message.

Q8. Can dynamic parameters be used to fetch API data?

Answer: Yes. A component can use a parameter such as productId to request the matching record from an API, with suitable loading and error handling.

19. Learning Checklist

  • Understand the purpose of dynamic route parameters.
  • Define route paths using colon-prefixed segments.
  • Use useParams() to read parameters.
  • Handle multiple dynamic parameters.
  • Navigate to dynamic URLs using Link.
  • Understand optional and catch-all route segments.
  • Know the difference between route and query parameters.
  • Validate values and handle missing records.
  • Build a small project using dynamic routes.

20. Conclusion

Dynamic Route Parameters make React applications flexible by allowing one route and component to display different records based on the URL. With Route, useParams(), and Link, you can create reusable product pages, user profiles, course details, and other data-driven experiences.

Learn more through JustAcademy React JS Training or Register for React JS Course Demo.

21. Official References

Previous Next
whatsapp