Route Parameters
In many applications, you need to create dynamic routes for example, a user profile page where the URL contains the user ID (`/user/123`). React Router allows you to define route parameters that capture these dynamic segments.
What are Route Parameters?
Route parameters are named segments in a route path that capture the value at that position in the URL. They are defined with a colon (`:`) followed by a parameter name.
Think of route parameters as placeholders that match any value. When a user visits `/user/42`, the parameter `:userId` captures `42`.
Defining a Route with Parameters
import { BrowserRouter, Routes, Route } from 'react-router-dom';import UserProfile from './UserProfile';
function App() { return ( <BrowserRouter> <Routes> <Route path="/user/:userId" element={<UserProfile />} /> </Routes> </BrowserRouter> );}Accessing Route Parameters with useParams
In the component rendered for that route, you can access the parameter values using the `useParams` hook.
import { useParams } from 'react-router-dom';
function UserProfile() { const { userId } = useParams(); <!-- userId will be the value from the URL, e.g., "123" -->
return <h1>User Profile for ID: {userId}</h1>;}Example: Product Details Page
// App.js<Route path="/products/:productId" element={<ProductDetails />} />
// ProductDetails.jsimport { useParams } from 'react-router-dom';import { useState, useEffect } from 'react';
function ProductDetails() { const { productId } = useParams(); const [product, setProduct] = useState(null);
useEffect(() => { <!-- Fetch product details using productId --> fetch(`/api/products/${productId}`) .then(res => res.json()) .then(setProduct); }, [productId]);
if (!product) return <p>Loading...</p>;
return ( <div> <h1>{product.name}</h1> <p>Price: ${product.price}</p> </div> );}Multiple Parameters
You can have multiple parameters in a route:
<Route path="/categories/:categoryId/products/:productId" element={...} />
<!-- In component -->const { categoryId, productId } = useParams();Optional Parameters and Catch-All
React Router also supports optional parameters and catch-all routes (like 404 pages).
<!-- Optional parameter using ? (not directly supported in v6, but you can use multiple routes) --><!-- Catch-all (404) route --><Route path="*" element={<NotFound />} />Two Minute Drill
- Route parameters let you capture dynamic segments of the URL, like `/user/:userId`.
- Use `useParams` hook to access the parameter values in your component.
- You can have multiple parameters in a single route.
- Parameters are always strings convert to numbers if needed.
- Use a catch-all route (`*`) for 404 pages.
Need more clarification?
Drop us an email at career@quipoinfotech.com
