URL parameters
- React course
- Intermediate
- Lesson 41/80
- 4 min
Learn to read :id style parameters with useParams.
URL parameters
In React Router you can mark part of a path as a parameter. The :id in /users/:id is a parameter; you read it with the useParams hook.
The name is free: :slug, :tab or :category. Multiple parameters are allowed too: /blog/:year/:slug.
The parameter always arrives as a string; if you need a number, convert with Number(id). At the end of this lesson you will write a product detail page.
Multiple parameters
Defining multiple parameters is easy: /blog/:year/:slug. In the component you destructure both from the same object: const { year, slug } = useParams();.
Parameters are not optional; if missing, the route does not match. For an optional segment use ?: /files/:name?. Then name may be undefined.
Order matters: /blog/:year/:slug and /blog/:slug/:year match differently.
Practice User detail
Complete the skeleton below. Write a UserDetail component; read id with useParams and return <p>User {id}</p>. Export it.
Starter code
import { useParams } from "react-router-dom";
// Write the UserDetail component hereSample solution
import { useParams } from "react-router-dom";
function UserDetail() {
const { id } = useParams();
return <p>User {id}</p>;
}
export default UserDetail;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does useParams return?
- Bir dizi
- Bir nesne Correct answer
- Bir dize
- A number
Explanation: useParams returns an object; keys are parameter names.
2 Reading parameter
const { id } = ____;
const { id } = useParams();
Explanation: The useParams() call returns the parameter object.
3 URL parameters: match the terms
| Term | Meaning |
|---|---|
useParams |
Reads a parameter |
:id |
Parameter marker |
Number(id) |
Converts to a number |
:name? |
Optional segment |