Dynamic Routing in React
# Dynamic Routing in React
1. Introduction
In the previous chapter, we learned how to map a static URL (/about) to a specific component (<About />). But modern web apps are dynamic. If a user clicks on an article, the URL might be /blog/123. If they view a profile, it's /user/alex. We cannot manually create routes for every user or post. Instead, we use Dynamic Routing with URL Parameters.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Define dynamic route paths using the colon
:syntax.
-
Extract parameters from the URL using the
useParamshook.
-
Implement programmatic navigation using the
useNavigatehook.
- Understand nested routing basics.
3. Beginner-Friendly Explanations
URL Parameters
A URL parameter acts as a variable inside your URL. Instead of defining a route aspath="/users/alex", you define it as path="/users/:username".
The colon : tells React Router: *"This part of the URL can be anything. Whatever the user types here, store it in a variable named 'username'."*
useParams and useNavigate
React Router provides powerful hooks to interact with the URL.
-
useParams(): Reads the dynamic variables from the URL so your component can use them (e.g., fetching user data based on the ID).
-
useNavigate(): A function that lets you change the URL via JavaScript code (e.g., redirecting a user to the login page after they click a "Logout" button), rather than relying on a user clicking a<Link>.
4. Syntax Explanation
Step 1: Defining a Dynamic Route
In yourApp.jsx, add a colon : before the dynamic part of the path.
```jsx id="ch18_ex1" import { Routes, Route } from 'react-router-dom'; import UserProfile from './UserProfile';
function App() { return ( <Routes> {/* Any URL matching /users/something will load UserProfile */} <Route path="/users/:userId" element={<UserProfile />} /> </Routes> ); }
jsx id="ch18_ex2" // Example React component import { useParams } from 'react-router-dom';
function UserProfile() { // Destructure the variable name exactly as you defined it in the Route! const { userId } = useParams();
// In a real app, you would use 'userId' in a useEffect to fetch data from an API. return <h1>Viewing Profile for User ID: {userId}</h1>; }
jsx id="ch18_ex3" // Example React component import { useNavigate } from 'react-router-dom';
function Checkout() { const navigate = useNavigate();
const handlePayment = () => { // Process payment logic... alert("Payment successful!"); // Redirect the user to the success page dynamically! navigate("/order-success"); };
return <button onClick={handlePayment}>Pay Now</button>; }
jsx id="ch18_proj1" // Example React component import React from 'react'; import { BrowserRouter, Routes, Route, Link, useParams, useNavigate } from 'react-router-dom';
// --- MOCK DATABASE --- const blogPosts = [ { id: '1', title: 'Why React is Great', content: 'React makes UI building easy...' }, { id: '2', title: 'Understanding Hooks', content: 'Hooks allow state in functional components...' }, ];
// --- LIST PAGE ---
const BlogList = () => (
<div className="p-8 max-w-2xl mx-auto">
<h1 className="text-3xl font-bold mb-6">Latest Articles</h1>
<div className="flex flex-col gap-4">
{blogPosts.map(post => (
<Link
key={post.id}
to={/post/${post.id}} // Dynamic Link!
className="block p-6 bg-white rounded-xl shadow-sm border hover:shadow-md transition text-blue-600 font-semibold text-lg"
>
{post.title} →
</Link>
))}
</div>
</div>
);
// --- DETAIL PAGE --- const BlogPostDetail = () => { const { id } = useParams(); // Extract ID from URL const navigate = useNavigate(); // Find the post in our mock database const post = blogPosts.find(p => p.id === id);
if (!post) { return <div className="p-8 text-red-500">Post not found!</div>; }
return ( <div className="p-8 max-w-2xl mx-auto bg-white min-h-screen"> <button onClick={() => navigate('/')} // Programmatic back button className="mb-6 text-sm font-bold text-gray-500 hover:text-black flex items-center gap-2" > ← Back to Articles </button> <h1 className="text-4xl font-black mb-4">{post.title}</h1> <p className="text-gray-600 leading-relaxed text-lg">{post.content}</p> </div> ); };
// --- APP ---
export default function App() {
return (
<BrowserRouter>
<div className="bg-gray-50 min-h-screen">
<Routes>
<Route path="/" element={<BlogList />} />
<Route path="/post/:id" element={<BlogPostDetail />} />
</Routes>
</div>
</BrowserRouter>
);
}
``
11. Coding Challenges
Challenge 1: Add a button to the BlogPostDetail component that says "Next Article". When clicked, it should programmatically navigate to the *next* post ID.
12. MCQs with Answers
Q1: How do you define a URL parameter in a Route path?
A) <Route path="/product/{id}" />
B) <Route path="/product/:id" />
C) <Route path="/product/id" />
*Answer: B*
Q2: Which hook allows you to extract variables directly from the URL?
A)
useLocation
B) useParams
C) useNavigate
*Answer: B*
13. Interview Questions
-
Q: How do you redirect a user to a different page after a form submission in React Router v6? *(Answer: Using the
useNavigate hook).*
-
Q: What is the difference between
<Link> and useNavigate?
14. FAQs
Can a route have multiple dynamic parameters?
Yes. <Route path="/category/:catId/product/:prodId" />. useParams() will return an object with both { catId, prodId }.
15. Summary
Dynamic routing is how React applications scale. By using the : syntax in your route paths, the useParams hook to read data, and useNavigate to control flow, you can build complex, data-driven applications that handle thousands of unique URLs using only a few components.
16. Next Chapter Recommendation
We know how to get an ID from the URL, but how do we get the actual data from a database? In Chapter 19: Fetching Data from APIs, we will learn how to connect our React frontend to a backend server using fetch() and useEffect`.