← Back to Chapters

Route Parameters

? Route Parameters

? Quick Overview

Route parameters allow React Router to create dynamic URLs such as /user/:id. These values can be read inside components using useParams().

? Key Concepts

  • Routes can include variables using :paramName
  • Values are extracted with useParams()
  • Supports multiple and optional parameters
  • Works with navigation links and programmatic routing

? Syntax & Theory

A route parameter is defined by prefixing a segment with a colon.

? View Code Example
// Route with a dynamic parameter named id
<Route path="/user/:id" element={<User />} />

? Basic Example

? View Code Example
// App.js defines a route with a dynamic id
import React from "react";
import { Routes, Route, Link } from "react-router-dom";
import User from "./User";

function App() {
return (
<div>
<Link to="/user/1">User 1</Link>
<Link to="/user/2">User 2</Link>
<Routes>
<Route path="/user/:id" element={<User />} />
</Routes>
</div>
);
}

export default App;
? View Code Example
// User.js reads the id parameter from the URL
import React from "react";
import { useParams } from "react-router-dom";

function User() {
const { id } = useParams();
return <p>User ID: {id}</p>;
}

export default User;

? Multiple Parameters

? View Code Example
// Route with multiple dynamic parameters
<Route path="/product/:category/:id" element={<Product />} />

? Optional Parameters

? View Code Example
// Optional parameter using question mark
<Route path="/blog/:postId?" element={<Blog />} />

⚙️ useNavigate with Parameters

? View Code Example
// Navigate to a dynamic route programmatically
import { useNavigate } from "react-router-dom";

const navigate = useNavigate();
navigate(`/user/${id}`);

? Interactive Simulator

Click the buttons below to simulate navigation and see how the Component extracts data from the URL.

 
example.com/user/john_doe

Component Render Output

const { id } = useParams();
id: "john_doe"

?️ Live Output / Explanation

Visiting /user/2 dynamically renders content for user ID 2. The same component adapts automatically for different values.

? Tips & Best Practices

  • Always validate parameter values
  • Prefer readable slugs over numeric IDs
  • Keep routes simple and predictable
  • Group related parameters logically

? Try It Yourself

  1. Create a dynamic user route
  2. Add multiple route parameters
  3. Use optional parameters
  4. Navigate using buttons