Lesson 43 of 60 – Route Parameters
72%

React Route Parameters

Route parameters allow you to create dynamic URLs in a React Router application. Instead of creating a separate route for every item, you can use a parameter to represent changing values such as a student ID, product ID, or post ID.

Note: Route parameters are commonly used when different URLs should display the same type of page with different data.

1. What are Route Parameters?

A route parameter is a dynamic part of a URL.

For example:

/students/101
/students/102
/students/103

Instead of creating three separate routes, one parameter can represent the student ID.

2. Why Use Route Parameters?

Route parameters are useful when the same page structure needs to display different data.

Common examples include:

  • Student IDs
  • Product IDs
  • Blog post IDs
  • User IDs
  • Course IDs

3. Dynamic URL Example

Consider these URLs:

/products/10
/products/20
/products/30

The product number changes, but the page structure can remain the same.

4. Creating a Route Parameter

A route parameter is created by placing a colon : before the parameter name.

<Route
    path="/products/:id"
    element={<Product />}
/>

Here, :id is the dynamic route parameter.

5. The :id Parameter

The :id parameter can represent different values.

/products/10
/products/20
/products/50

All of these URLs can match:

path="/products/:id"

6. Accessing Parameters with useParams

React Router provides the useParams Hook to read route parameters inside a component.

import { useParams } from "react-router-dom";

function Product() {

    const params = useParams();

    return (
        <h2>Product ID: {params.id}</h2>
    );
}

7. Destructuring useParams

Instead of accessing the parameter through the complete object, you can destructure it.

import { useParams } from "react-router-dom";

function Product() {

    const { id } = useParams();

    return (
        <h2>Product ID: {id}</h2>
    );
}

8. Creating a Student Route

Suppose we want to create a page for individual students.

<Route
    path="/students/:id"
    element={<Student />}
/>

The :id value can represent different students.

9. Reading Student ID

import { useParams } from "react-router-dom";

function Student() {

    const { id } = useParams();

    return (
        <h1>Student ID: {id}</h1>
    );
}

If the URL is /students/101, the value of id will represent 101.

10. Route Parameter Workflow

The basic workflow is:

URL
 ↓
Route Parameter
 ↓
useParams()
 ↓
Component
 ↓
Display Data

This pattern is commonly used for detail pages.

11. Creating a Product Detail Page

A product detail route can use an ID parameter.

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

The same component can display different products.

12. Reading Product ID

import { useParams } from "react-router-dom";

function ProductDetails() {

    const { id } = useParams();

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

13. Dynamic Links

You can create a Link whose destination contains a dynamic value.

<Link to="/products/101">
    Product 101
</Link>

When clicked, the URL becomes /products/101.

14. Dynamic Link with a Variable

A variable can be used to create a dynamic Link.

const productId = 101;

<Link to={`/products/${productId}`}>
    View Product
</Link>

The value of productId is inserted into the URL.

15. Student List with Dynamic Links

const students = [
    { id: 101, name: "Rahul" },
    { id: 102, name: "Amit" },
    { id: 103, name: "Priya" }
];

function StudentList() {

    return (
        <div>

            {students.map(student => (
                <div key={student.id}>

                    <h3>{student.name}</h3>

                    <Link
                        to={`/students/${student.id}`}
                    >
                        View Student
                    </Link>

                </div>
            ))}

        </div>
    );
}

16. Multiple Route Parameters

A route can contain more than one parameter.

<Route
    path="/students/:studentId/courses/:courseId"
    element={<Course />}
/>

This route contains two parameters:

  • studentId
  • courseId

17. Reading Multiple Parameters

import { useParams } from "react-router-dom";

function Course() {

    const {
        studentId,
        courseId
    } = useParams();

    return (
        <div>
            <p>Student: {studentId}</p>
            <p>Course: {courseId}</p>
        </div>
    );
}

18. Route Parameter Names

You can choose meaningful names for route parameters.

/students/:studentId
/products/:productId
/courses/:courseId
/posts/:postId

Meaningful parameter names make the application easier to understand.

19. Parameters Are URL Values

Route parameters are values taken from the URL.

/students/105

For this route:

path="/students/:id"

The id parameter represents the value from the URL.

20. Using Parameters to Fetch Data

A route parameter can be used when requesting data from an API.

const { id } = useParams();

useEffect(() => {

    fetch(`/api/students/${id}`)
        .then(response => response.json())
        .then(data => {
            console.log(data);
        });

}, [id]);

Here, the parameter can identify which student's data should be requested.

21. Parameters and useEffect

When a route parameter is used in an effect, it can be included in the dependency array.

const { id } = useParams();

useEffect(() => {

    console.log("Current ID:", id);

}, [id]);

This allows the effect to respond when the parameter value changes.

22. Parameter Values Are Strings

Values obtained from URL parameters are generally strings.

const { id } = useParams();

console.log(typeof id);

If you need a number for a calculation, convert the value explicitly.

const numericId = Number(id);

23. Numeric Parameter Example

const { id } = useParams();

const studentId = Number(id);

console.log(studentId);

Explicit conversion can be useful when an application expects a numeric ID.

24. Complete Student Route Example

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

function Student() {

    const { id } = useParams();

    return (
        <div>
            <h2>Student Details</h2>
            <p>Student ID: {id}</p>
        </div>
    );
}

function Home() {

    return (
        <div>

            <h2>Students</h2>

            <Link to="/students/101">
                Rahul
            </Link>

            <br />

            <Link to="/students/102">
                Amit
            </Link>

        </div>
    );
}

function App() {

    return (
        <BrowserRouter>

            <Routes>

                <Route
                    path="/"
                    element={<Home />}
                />

                <Route
                    path="/students/:id"
                    element={<Student />}
                />

            </Routes>

        </BrowserRouter>
    );
}

export default App;

25. Parameters with Nested URLs

Parameters can also be part of longer URL structures.

/students/101/profile
/students/101/courses
/students/101/results

A parameter such as :id can represent the student in these URLs.

26. Common Route Parameter Mistakes

  • Forgetting the colon before the parameter name.
  • Using the wrong parameter name in useParams().
  • Forgetting to import useParams.
  • Using a route parameter without defining the route.
  • Assuming URL parameters are automatically numbers.
  • Creating incorrect dynamic Links.
  • Using the wrong URL structure.
// Correct
path="/students/:id"

// Incorrect
path="/students/id"

27. Route Parameters with Cards

Route parameters are useful for product, course, or student cards.

function ProductCard({ product }) {

    return (
        <div className="card">

            <h3>{product.name}</h3>

            <Link
                to={`/products/${product.id}`}
            >
                View Details
            </Link>

        </div>
    );
}

28. Route Parameter Workflow

A common workflow is:

1. Create dynamic route
        ↓
2. Add parameter with :
        ↓
3. Create Link with a value
        ↓
4. User clicks Link
        ↓
5. URL contains parameter
        ↓
6. useParams() reads parameter
        ↓
7. Component uses the value
        ↓
8. Data is displayed

29. Complete Product Parameter Example

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

function Product() {

    const { id } = useParams();

    return (
        <div>

            <h2>Product Details</h2>

            <p>
                Product ID: {id}
            </p>

        </div>
    );
}

function Home() {

    return (
        <div>

            <h2>Products</h2>

            <Link to="/products/101">
                Product 101
            </Link>

            <br />

            <Link to="/products/102">
                Product 102
            </Link>

        </div>
    );
}

function App() {

    return (
        <BrowserRouter>

            <Routes>

                <Route
                    path="/"
                    element={<Home />}
                />

                <Route
                    path="/products/:id"
                    element={<Product />}
                />

            </Routes>

        </BrowserRouter>
    );
}

export default App;

30. Route Parameter Best Practices

  • Use meaningful parameter names such as :studentId.
  • Use useParams() to read route parameters.
  • Remember that URL parameters are generally strings.
  • Convert values to numbers when numeric operations are required.
  • Use dynamic Links to create parameter-based navigation.
  • Keep route structures simple and meaningful.
  • Validate parameter values when loading external data.
  • Handle missing or invalid IDs appropriately.
  • Include changing parameters in relevant effect dependencies.
  • Use route parameters for detail pages and dynamic resources.
/students/:id
        ↓
useParams()
        ↓
id
        ↓
Student Data

📌 Key Points

  • Route parameters create dynamic URLs.
  • A colon : is used before a parameter name.
  • useParams() reads route parameters.
  • Parameters can be used for students, products, posts, courses, and users.
  • Dynamic Links can include parameter values.
  • URL parameter values are generally strings.
  • Multiple parameters can be used in one route.
  • Parameters are especially useful for detail pages.

🧠 Quick Quiz

Question: Which Hook is used to read route parameters in React Router?