π Passing Data Through URLs
In React Router:
URLs can carry dynamic values
These values are called route parameters
Used for:
User profiles
Product pages
Blog posts
Example URL:
/users/42
/products/iphone-15π What Is a Dynamic Route?
A route that contains variables instead of fixed values.
Syntax
<Route path="/users/:id" element={<UserProfile />} />:idβ dynamic parameteridcan be any value (1,abc,john)
Example URLs
URL | id value |
|---|---|
|
|
|
|
πͺ What Is useParams()?
A hook provided by React Router
Used to read dynamic values from the URL
Returns an object of parameters
Basic Syntax
const params = useParams();or
const { id } = useParams();π§βπ» Hands-On: User Profile Page
Route Definition (App.jsx)
<Route path="/users/:id" element={<UserProfile />} />src/pages/UserProfile.jsx
import { useParams } from 'react-router-dom';
function UserProfile() {
const { id } = useParams();
return (
<div>
<h2>User Profile</h2>
<p>User ID: {id}</p>
</div>
);
}
export default UserProfile;Navigate to User Profile
<Link to="/users/101">View User 101</Link>π¦ Product Details Page (Real-World Example)
Route Definition
<Route path="/products/:productId" element={<ProductDetails />} />src/pages/ProductDetails.jsx
import { useParams } from 'react-router-dom';
function ProductDetails() {
const { productId } = useParams();
return (
<div>
<h2>Product Details</h2>
<p>Product ID: {productId}</p>
</div>
);
}
export default ProductDetails;β οΈ Common Mistakes
β Forgetting
:before param nameβ Using
useParams()outside Routerβ Expecting number instead of string
β When to Use Dynamic Routes
Use Case | Example |
|---|---|
User profile |
|
Product page |
|
Blog post |
|