Popular Searches
Popular Course Categories
Popular Courses

Dynamic Route Parameters

Dynamic Route Parameters

React Router

Dynamic Route Parameters in React JS

Dynamic Route Parameters are used in React Router to create routes that can display different content based on values in the URL. They are useful for product details, student profiles, blog posts, user dashboards, and other pages where the content changes according to an ID or name.

React JS Training: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. What Are Dynamic Route Parameters?

Dynamic Route Parameters are variable parts of a route path. In React Router, a dynamic segment starts with a colon (:) followed by a parameter name.

For example:

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

Here, :productId is a dynamic route parameter. It can match different values in the URL.

URL Parameter Value
/products/101 productId = "101"
/products/205 productId = "205"
/products/phone productId = "phone"

The same route pattern can therefore display different content depending on the value supplied in the URL.


2. Why Do We Need Dynamic Route Parameters?

Without dynamic parameters, developers may need to create a separate route for every product, user, or article. Dynamic parameters allow one route pattern to handle many different values.

  • Display individual product details.
  • Open a particular user's profile.
  • Display a specific blog post.
  • Show student information using a student ID.
  • Display order details using an order number.
  • Create reusable detail pages for data-driven applications.

3. Installing React Router

If React Router is not already installed, open your terminal in the project directory and run:

npm install react-router

The examples below use the current declarative routing API with imports from react-router. If your existing project uses a different React Router version, follow that version's package and import conventions.


4. Setting Up BrowserRouter

BrowserRouter provides the routing context required by React Router components and hooks.

In src/main.jsx:

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

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

Now components inside App can use Routes, Route, Link, and routing hooks such as useParams.


5. Creating Your First Dynamic Route

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

Step 1: Define the Route

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

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

export default App;

The :productId segment tells React Router to capture that part of the URL as a parameter.

Step 2: Read the Parameter with useParams

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

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;

Example result: When the user opens /products/101, the page displays Product ID: 101.


6. Understanding useParams()

useParams() is a React Router hook used to access parameters from the matched route. The parameter names in the returned object correspond to the names used in the route path.

Syntax

import { useParams } from "react-router";

const params = useParams();

Example

// Route definition:
<Route path="/users/:userId" element={<UserProfile />} />

// Inside UserProfile:
const { userId } = useParams();

If the URL is /users/25, the value of userId is the string "25".

Important Points

  • Parameter names must match the names defined in the route path.
  • Route parameters are normally returned as strings.
  • Child routes inherit parameters from their parent routes.
  • Use the parameter to select the relevant record or content.
  • Validate parameters before using them in calculations or data requests.

7. Using Multiple Dynamic Route Parameters

A route can contain more than one dynamic parameter. This is useful when a page depends on multiple values.

Route Definition

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

Component Example

import { useParams } from "react-router";

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

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

export default ProductDetails;

For the URL /categories/5/products/101, the parameter values are categoryId = "5" and productId = "101".


8. Dynamic Routes with Link

The Link component can navigate to a dynamic route by including the desired parameter value in the destination path.

import { Link } from "react-router";

function ProductList() {
  return (
    <div>
      <h2>Products</h2>
      <Link to="/products/101">View Product 101</Link>
      <br />
      <Link to="/products/205">View Product 205</Link>
    </div>
  );
}

export default ProductList;

Clicking each link opens the same ProductDetails route with a different product ID.


9. Complete Example: Product Listing and Details

This example demonstrates how a list of products can link to a reusable product details page.

App.jsx

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

const products = [
  { id: "101", name: "Laptop", price: 55000 },
  { id: "102", name: "Mobile Phone", price: 25000 },
  { id: "103", name: "Headphones", price: 2000 }
];

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

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

  if (!product) {
    return <h2>Product Not Found</h2>;
  }

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

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

How it works:

  1. The ProductList component displays the available products.
  2. Each Link includes the product's ID in the URL.
  3. The dynamic route matches the URL.
  4. useParams reads the productId value.
  5. The component finds and displays the matching product.
  6. If no matching product exists, a Product Not Found message is displayed.

10. Dynamic Routes for User Profiles

Dynamic parameters can also be used to create profile pages for different users.

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

function UserProfile() {
  const { userId } = useParams();

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

function App() {
  return (
    <div>
      <nav>
        <Link to="/users/1">User 1</Link> |{" "}
        <Link to="/users/2">User 2</Link>
      </nav>
      <Routes>
        <Route path="/users/:userId" element={<UserProfile />} />
      </Routes>
    </div>
  );
}

export default App;

Both user links use the same component, but the displayed ID changes according to the URL.


11. Dynamic Route Parameters vs Query Parameters

Route parameters and query parameters are both used to pass values through URLs, but they serve different purposes.

Feature Route Parameters Query Parameters
Location Part of the URL path. Appear after a question mark.
Example /products/101 /products?category=electronics
Typical use Identify a particular record or resource. Filtering, searching, sorting, or pagination.
React Router hook useParams() useSearchParams()

Example of Query Parameters

import { useSearchParams } from "react-router";

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

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

For a URL such as /products?category=electronics, the category value is electronics. This is a query parameter, not a route parameter.


12. Optional and Catch-All Route Segments

Optional Route Segment

In supported React Router versions, a question mark can make a route segment optional.

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

This route can match /about and a language-specific path such as /en/about.

Catch-All Route Segment

A route ending with /* can match the remaining path, including additional slashes.

<Route path="/files/*" element={<FileViewer />} />

The remaining matched path can be read through useParams() using the "*" key.

import { useParams } from "react-router";

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

  return <p>File path: {filePath}</p>;
}

13. Validating Dynamic Route Parameters

Dynamic parameters come from the URL, so you should not assume that every value is valid. Validate values before using them to look up data, call an API, or perform calculations.

Example: Validate a Numeric ID

import { useParams } from "react-router";

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

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

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

Validation in the frontend improves user experience, but the backend must also validate IDs and enforce authorization before returning protected data.


14. Common Mistakes and Solutions

Mistake Solution
Forgetting the colon before a parameter name. Use a pattern such as /users/:userId.
Using the wrong parameter name in useParams. Ensure the destructured name matches the route definition.
Expecting a parameter to be a number. Remember that route parameter values are normally strings; convert and validate when needed.
Using Link outside a router. Render Link inside BrowserRouter or another suitable router.
Assuming a route parameter automatically fetches data. Use the parameter to select data or trigger an appropriate data-loading operation.
Not handling an unknown ID. Display a not-found message or use an appropriate error-handling approach.
Using duplicate parameter names within one route path. Give each dynamic segment a unique name.

15. Best Practices

  • Use meaningful parameter names such as productId, userId, and postId.
  • Use one reusable component for records that share the same page structure.
  • Validate and convert parameter values when required.
  • Handle missing records and invalid IDs gracefully.
  • Use Link or NavLink to navigate to dynamic routes.
  • Use route parameters for resource identity and query parameters for filtering or sorting.
  • Avoid exposing sensitive information in URLs.
  • Never rely on frontend validation alone for security or authorization.

16. Real-World Applications

  • E-commerce: /products/101 displays a particular product.
  • Education portal: /students/25 displays a student's details.
  • Blog application: /posts/react-basics can display an article identified by its slug.
  • User management: /users/42 displays a user's profile.
  • Order management: /orders/5001 identifies an order details page.
  • Travel application: /destinations/paris displays information about a destination.

17. Interview Questions and Answers

Q1. What are dynamic route parameters?

They are variable segments in a route path that allow a route to match different URL values.

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

Use a colon-prefixed segment, such as } />.

Q3. What is useParams()?

useParams is a React Router hook that returns the dynamic parameters from the currently matched route.

Q4. What does useParams() return?

It returns an object whose properties correspond to the parameter names in the matched route. Values are normally strings.

Q5. Can one route contain multiple parameters?

Yes. For example, /categories/:categoryId/products/:productId defines two parameters.

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

Route parameters are part of the URL path, while query parameters appear after the question mark and are commonly used for filtering, searching, and pagination.

Q7. Can dynamic routes display data from an API?

Yes. A route parameter can identify the record to request from an API. The application must implement the data-fetching and error-handling logic.

Q8. Why should route parameters be validated?

Users can manually change URL values. Validation helps prevent invalid lookups and improves error handling, while server-side checks protect sensitive operations.


18. Practice Exercises

  1. Create a React project and install React Router.
  2. Set up BrowserRouter, Routes, and Route.
  3. Create a dynamic route for product details using :productId.
  4. Use useParams to display the selected product ID.
  5. Create a list of products with Link components to their detail pages.
  6. Add a dynamic user profile route using :userId.
  7. Create a route with two dynamic parameters.
  8. Display a friendly message when a record is not found.
  9. Experiment with query parameters using useSearchParams.

19. Quick Revision Checklist

  • Understand the purpose of dynamic route parameters.
  • Know how to define a route using a colon-prefixed segment.
  • Understand how useParams retrieves route values.
  • Practice using multiple parameters.
  • Know how to create links to dynamic routes.
  • Understand the difference between route and query parameters.
  • Validate parameters and handle missing records.
  • Test your routes with different URL values.

20. Official Documentation and Course Links

Conclusion

Dynamic Route Parameters make React applications flexible by allowing one route to display different content based on URL values. By combining Route, Link, and useParams, developers can build reusable product pages, user profiles, blog details, and other data-driven interfaces. Always validate incoming parameters and handle missing records to create a reliable application.

whatsapp