Skip to main content
React Introduction
CHAPTER 18 Beginner

Dynamic Routing in React

Updated: May 13, 2026
20 min read

# 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 useParams hook.
  • Implement programmatic navigation using the useNavigate hook.
  • 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 as path="/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 your App.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> ); }

123
### Step 2: Extracting the Parameter
Inside `UserProfile.jsx`, use the `useParams` hook to read the `userId` from the URL.

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>; }

123
### Step 3: Programmatic Navigation
Sometimes you need to navigate via logic, not a click.

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>; }

1234567891011121314151617181920212223
## 5. Output Explanations
If a user navigates to `yourapp.com/users/45`, React Router matches it to `/users/:userId`. The `<UserProfile>` component renders, `useParams` extracts `{ userId: "45" }`, and the screen displays "Viewing Profile for User ID: 45".

## 6. Real-World Examples
- **E-commerce:** `/product/:productId` => `/product/nike-shoes-123`
- **Social Media:** `/:username/status/:tweetId` => `/elonmusk/status/555123` (Notice you can have multiple parameters in one route!)
- **Programmatic Navigation:** Redirecting to `/login` if an API request returns an "Unauthorized" error.

## 7. Common Mistakes
- **Typo in destructuring:** Defining the route as `path="/post/:id"` but trying to extract `const { postId } = useParams()`. They must match perfectly!
- **Not handling loading states:** When fetching data based on an ID, the data isn't available instantly. You must handle the loading state while the `useEffect` fetches the data.

## 8. Best Practices
- Use clear, descriptive parameter names (e.g., `:slug`, `:productId`, `:orderId` rather than just `:id`).
- When navigating programmatically, use `navigate(-1)` to mimic the browser's "Back" button.

## 9. Exercises
1. Create a dynamic route for `/article/:slug`.
2. Create an `ArticleView` component that extracts the `slug` and displays it in an `<h1>` tag.

## 10. Mini Project: Blog Detail Page
Let's build a mini-app with a list of blogs that navigate to a dynamic detail page.

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} &rarr; </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" > &larr; 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`.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·