URL Parameters and useParams
In this lesson, we will learn how to create dynamic routes, pass identifiers through URLs, and read those values using the useParams hook.
1. What Are URL Parameters?
URL parameters are values included in a URL to identify a particular resource. They are useful when many records share the same page structure but each record has different information.
For example, a training institute may have many students. Instead of creating a separate component for every student, we can create one StudentDetails component and pass a different student ID through the URL.
Remember: A URL parameter lets a route receive a changing value without creating a separate route definition for every possible value.
2. What Is a Dynamic Route?
A dynamic route contains a parameter whose value can change. In React Router, a parameter is declared by placing a colon before its name in the route path.
Route Definition
<Route
path="/students/:studentId"
element={<StudentDetails />}
/>
Here, :studentId is a dynamic parameter. React Router can match URLs such as:
- /students/101
- /students/102
- /students/205
All these URLs can render the same StudentDetails component. The value of studentId changes according to the URL.
3. What Is the useParams Hook?
useParams is a React Router hook that returns an object containing the dynamic parameters from the currently matched route.
Import useParams
import { useParams } from 'react-router-dom';
Basic Syntax
const params = useParams();
If the current URL is /students/101 and the route path is /students/:studentId, useParams returns an object similar to:
{
studentId: "101"
}
Important: URL parameters are strings. If you need a number for calculations or numeric comparisons, convert and validate the value explicitly.
4. Read a Student ID Using useParams
Let's create a StudentDetails component that reads the student ID from the current URL and displays it on the page.
import { useParams } from 'react-router-dom';
function StudentDetails() {
const { studentId } = useParams();
return (
<div>
<h2>Student Details</h2>
<p>Student ID: {studentId}</p>
</div>
);
}
export default StudentDetails;
Explanation
- Import useParams from React Router.
- Call useParams inside StudentDetails.
- Extract the studentId parameter from the returned object.
- Display studentId using JSX.
Expected Output
When the URL is /students/101:
Student Details
Student ID: 101
When the URL is /students/205:
Student Details
Student ID: 205
5. Configure a Dynamic Route
The route parameter must be defined in the Route path before the component can read it using useParams.
import {
BrowserRouter,
Routes,
Route
} from 'react-router-dom';
import StudentDetails from './StudentDetails';
function App() {
return (
<BrowserRouter>
<Routes>
<Route
path="/students/:studentId"
element={<StudentDetails />}
/>
</Routes>
</BrowserRouter>
);
}
export default App;
If BrowserRouter is already configured in main.jsx, do not add another BrowserRouter in App.jsx. Place Routes directly inside the existing router instead.
6. Use Multiple URL Parameters
A route can contain more than one dynamic parameter. For example, a course may belong to a particular student.
Route Definition
<Route
path="/students/:studentId/courses/:courseId"
element={<StudentCourseDetails />}
/>
Read Both Parameters
import { useParams } from 'react-router-dom';
function StudentCourseDetails() {
const { studentId, courseId } = useParams();
return (
<div>
<h2>Student Course Details</h2>
<p>Student ID: {studentId}</p>
<p>Course ID: {courseId}</p>
</div>
);
}
export default StudentCourseDetails;
Example URL
/students/101/courses/25
Expected Output
Student Course Details
Student ID: 101
Course ID: 25
7. Dynamic Course Details Page
A common real-world example is displaying different course details using a course ID in the URL.
import { useParams } from 'react-router-dom';
const courses = {
"101": "React Development",
"102": "Dot Net Development",
"103": "Data Analytics"
};
function CourseDetails() {
const { courseId } = useParams();
const courseName = courses[courseId];
if (!courseName) {
return <h2>Course Not Found</h2>;
}
return (
<div>
<h2>Course Details</h2>
<p>Course ID: {courseId}</p>
<p>Course Name: {courseName}</p>
</div>
);
}
export default CourseDetails;
In this example, the course information is stored in a JavaScript object for demonstration. A real application can fetch course details from an API using the course ID.
Expected Output for /courses/101
Course Details
Course ID: 101
Course Name: React Development
Expected Output for /courses/999
Course Not Found
8. URL Parameters vs Query Parameters
URL parameters and query parameters both carry information in a URL, but they use different formats and are accessed differently.
| Feature | URL Parameter | Query Parameter |
|---|---|---|
| Example URL | /courses/101 | /courses?category=react |
| Location | Part of the route path | After the question mark (?) |
| Common use | Identifying a particular resource | Filtering, sorting, and search options |
| Typical access | useParams() | useLocation() with URLSearchParams |
Remember: useParams reads parameters declared in the route path. Query parameters such as category=react are usually read from the URL search string.
9. Common Mistakes
Mistake 1: Forgetting the colon
// Dynamic parameter
<Route path="/students/:studentId" element={<StudentDetails />} />
The colon identifies studentId as a dynamic route parameter.
Mistake 2: Using a different parameter name
If the route uses :studentId, read studentId from useParams. The property name must match the name defined in the route.
Mistake 3: Treating a URL parameter as a number
Parameters are strings. Convert and validate them before performing numeric operations.
const { studentId } = useParams();
const id = Number(studentId);
if (!Number.isInteger(id) || id <= 0) {
return <h2>Invalid Student ID</h2>;
}
Mistake 4: Expecting a missing record to be handled automatically
useParams reads the parameter value; it does not check whether a corresponding student or course exists. Your application must handle missing records separately.
Practice Tasks
- Create a dynamic route for /students/:studentId.
- Display the student ID using useParams.
- Create a route for /courses/:courseId.
- Display a course name based on the course ID.
- Create a route with studentId and courseId parameters.
- Display both values using useParams.
- Handle an invalid course ID with a Course Not Found message.
- Explain the difference between URL parameters and query parameters.
- Validate a numeric ID before using it in a calculation.
Summary
Dynamic routes allow a single React component to display different information based on URL values. Parameters are defined with a colon in the route path, such as /students/:studentId, and the useParams hook reads those values from the matched route. You can use one or multiple parameters for student details, course details, and other dynamic pages. Remember that URL parameters are strings and that your application must handle invalid values or missing records. In the next lesson, we will learn nested routes.