React Mastery / Routing (React Router)

Dynamic Routes and Routes Parameter

🌐 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 parameter

  • id can be any value (1, abc, john)

Example URLs

URL

id value

/users/1

1

/users/john

john


πŸͺ 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

/users/:id

Product page

/products/:productId

Blog post

/blog/:slug