How to Use URL Parameters in React Router
๐ How to Use URL Parameters in React Router (v6+)
URL parameters (also called route parameters) allow you to pass dynamic values through the URL in a React app. These are very useful when building detail pages like /user/123 or /product/42.
๐ฆ Step-by-Step Guide
✅ 1. Install React Router (if you haven’t already)
bash
Copy
Edit
npm install react-router-dom
✅ 2. Define a Route with a Parameter
In your routing setup (usually in App.js or routes.js):
jsx
Copy
Edit
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './Home';
import UserProfile from './UserProfile';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/user/:id" element={<UserProfile />} />
</Routes>
</BrowserRouter>
);
}
export default App;
๐ :id is a URL parameter that will change based on the user.
✅ 3. Access the URL Parameter Inside a Component
In UserProfile.js:
jsx
Copy
Edit
import React from 'react';
import { useParams } from 'react-router-dom';
function UserProfile() {
const { id } = useParams(); // get the "id" from the URL
return (
<div>
<h2>User Profile</h2>
<p>User ID: {id}</p>
</div>
);
}
export default UserProfile;
๐ฏ useParams() gives you an object with all the route parameters.
✅ 4. Navigate to the Route with Parameters
You can link to a specific user profile like this:
jsx
Copy
Edit
import { Link } from 'react-router-dom';
<Link to="/user/123">View User 123</Link>
Or programmatically using useNavigate():
jsx
Copy
Edit
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/user/123');
๐ง Use Cases for URL Parameters
/post/:postId → Blog post detail page
/product/:productId → Product detail
/category/:name/page/:pageNum → Paginated categories
✅ Summary
Step What to Do
1️⃣ Define route with :paramName
2️⃣ Use useParams() to access the value
3️⃣ Link to the route using <Link to="/path/value">
Learn React JS Course in Hyderabad
Read More
Programmatic Navigation in React
Nested Routes in React Explained
๐ React Router & Navigation
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment