Route Parameters
Introduction
Route parameters in React Router allow you to capture dynamic values from the URL and use them in your components. This enables you to create routes that adapt based on specific parameters such as user IDs, product IDs, or other identifiers. Route parameters are essential for building responsive and interactive applications, especially when you need to display personalized or context-specific content.
In this lesson, you’ll learn:
- What route parameters are and how to define them
- How to access route parameters using
useParams
- Best practices for working with multiple parameters and nested routes
What are Route Parameters?
Route parameters are variables embedded in the URL that represent unique identifiers or specific data points. In React Router, route parameters are defined by prefixing the parameter name with a colon (:
) in the route path.
For example:
<Route path="/user/:userId" element={<User />} />
Here, :userId
is a route parameter. When a user navigates to /user/123
, 123
is captured as the userId
parameter.
Defining Route Parameters
To define a route with parameters, use the path
prop in the <Route />
component and include a colon followed by the parameter name.
Example: Setting Up Route Parameters
import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import UserProfile from './components/UserProfile';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/user/:userId" element={<UserProfile />} />
</Routes>
</BrowserRouter>
);
}
export default App;
In this example:
- The route
/user/:userId
expects a parameter calleduserId
. - Navigating to
/user/123
or/user/456
will render theUserProfile
component, passing the uniqueuserId
parameter from the URL.
Accessing Route Parameters with useParams
To retrieve and use route parameters in a component, use React Router’s useParams
hook. This hook returns an object containing the route parameters, which you can then use in the component.
Example: Using useParams
to Access Route Parameters
import React from 'react';
import { useParams } from 'react-router-dom';
function UserProfile() {
const { userId } = useParams();
return (
<div>
<h2>User Profile</h2>
<p>User ID: {userId}</p>
</div>
);
}
export default UserProfile;
In this example:
- The
useParams
hook returns an object with keys matching the route parameters. userId
is captured from the URL (e.g.,/user/123
) and used in the component to display information.
Example Use Cases for Route Parameters
Route parameters are versatile and useful in various application scenarios. Here are some common examples:
- User Profiles: Access individual user profiles based on a unique user ID.
- Route:
/user/:userId
- Route:
- Product Details: View product details using a product ID in the URL.
- Route:
/product/:productId
- Route:
- Blog Posts: Display a blog post based on its unique post ID.
- Route:
/post/:postId
- Route:
Working with Multiple Route Parameters
Sometimes, you may need multiple parameters in a single route. React Router allows you to add as many parameters as you need, each separated by a slash.
Example: Defining Multiple Route Parameters
<Route path="/category/:categoryId/product/:productId" element={<ProductDetail />} />
To access multiple parameters, use useParams
as shown below:
import React from 'react';
import { useParams } from 'react-router-dom';
function ProductDetail() {
const { categoryId, productId } = useParams();
return (
<div>
<h2>Product Details</h2>
<p>Category ID: {categoryId}</p>
<p>Product ID: {productId}</p>
</div>
);
}
export default ProductDetail;
In this example:
- Both
categoryId
andproductId
are extracted from the URL. - The component can use both parameters to fetch data or render specific content.
Nested Route Parameters
Nested route parameters allow you to manage relationships between entities, such as categories and products or users and orders. With nested routes, you can define a main route with multiple sub-routes, each with its own parameters.
Example: Using Nested Route Parameters
Define the nested routes:
import { Routes, Route } from 'react-router-dom';
import Category from './components/Category';
import Product from './components/Product';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/category/:categoryId" element={<Category />}>
<Route path="product/:productId" element={<Product />} />
</Route>
</Routes>
</BrowserRouter>
);
}
In this example:
- The
categoryId
parameter is used in theCategory
component. - The
productId
parameter is used in theProduct
component nested withinCategory
.
Using Route Parameters for Data Fetching
One of the most practical uses of route parameters is data fetching. For example, you can use the userId
parameter to fetch user data from an API.
Example: Fetching Data Based on Route Parameters
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
function UserProfile() {
const { userId } = useParams();
const [user, setUser] = useState(null);
useEffect(() => {
const fetchUser = async () => {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
setUser(data);
};
fetchUser();
}, [userId]);
if (!user) return <p>Loading...</p>;
return (
<div>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>Username: {user.username}</p>
</div>
);
}
export default UserProfile;
In this example:
- The component fetches user data based on the
userId
parameter in the URL. - The
useEffect
hook ensures that data is fetched each timeuserId
changes.
Error Handling with Route Parameters
When working with route parameters, handling errors such as invalid IDs or missing data is important for a seamless user experience.
Example: Handling Errors for Invalid Route Parameters
function UserProfile() {
const { userId } = useParams();
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const fetchUser = async () => {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) throw new Error('User not found');
const data = await response.json();
setUser(data);
} catch (err) {
setError(err.message);
}
};
fetchUser();
}, [userId]);
if (error) return <p>{error}</p>;
if (!user) return <p>Loading...</p>;
return (
<div>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>Username: {user.username}</p>
</div>
);
}
In this example:
- If the
userId
is invalid or not found, an error message is displayed instead of loading indefinitely. - The
error
state holds the error message, and the component renders it conditionally.
Tips for Using Route Parameters
- Use Descriptive Parameter Names: Choose names that make it clear what each parameter represents (e.g.,
userId
vs.id
). - Handle Missing or Invalid Parameters: Check for missing or invalid data to prevent broken pages.
- Optimize Data Fetching: Only fetch data when necessary, using
useEffect
dependencies to avoid unnecessary API calls.
Conclusion
In this lesson, you learned:
- What route parameters are and how to use them
- How to access and manage route parameters with
useParams
- Techniques for handling multiple parameters, nested routes, and error handling
Route parameters are crucial for building dynamic, data-driven applications in React. In the next module, we’ll explore state management using the Context API and Redux to manage data more effectively across your app.