Route Parameters
Learn to handle dynamic routes and URL parameters in React Router. This is a foundational concept in component-based UI development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world React experience. Take your time with each section and practice the examples
URL Parameters
URL parameters allow you to create dynamic routes that can accept different values. They are defined in the route path using a colon followed by the parameter name.. This is an essential concept that every React developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Basic URL Parameters
// Route with parameter
<Route path="/user/:id" element={<UserProfile />} />
// Component using useParams
import { useParams } from 'react-router-dom';
function UserProfile() {
const { id } = useParams();
return (
<div>
<h1>User Profile</h1>
<p>User ID: {id}</p>
</div>
);
}
// Multiple parameters
<Route path="/user/:id/posts/:postId" element={<UserPost />} />
function UserPost() {
const { id, postId } = useParams();
return (
<div>
<h1>User Post</h1>
<p>User ID: {id}</p>
<p>Post ID: {postId}</p>
</div>
);
}Query Parameters
// Using query parameters
import { useSearchParams } from 'react-router-dom';
function ProductList() {
const [searchParams, setSearchParams] = useSearchParams();
const category = searchParams.get('category');
const sort = searchParams.get('sort');
return (
<div>
<h1>Products</h1>
<p>Category: {category}</p>
<p>Sort: {sort}</p>
<button onClick={() => setSearchParams({ category: 'electronics' })}>
Electronics
</button>
<button onClick={() => setSearchParams({ sort: 'price' })}>
Sort by Price
</button>
</div>
);
}