React Router URL Parameters

Introduction

Modern web applications often display dynamic content based on URLs. For example:


/products/5
/user/10
/blog/react-router-guide

In these URLs:

  • 5
  • 10
  • react-router-guide

are dynamic values.

React applications commonly use React Router for handling navigation and routing. React Router provides a feature called URL Parameters that allows developers to create dynamic routes and access values directly from the URL.

What are URL Parameters in ReactJS?

URL Parameters are dynamic values added inside a URL path.

These parameters help React applications display different content based on the URL.

Example


/user/5

Here:

  • /user is the route
  • 5 is the parameter value

Dynamic Route Example


<Route path="/user/:id" element={} />

In this example:

  • :id is a URL parameter
  • It can hold dynamic values

Why URL Parameters are Used?

URL parameters are useful when the same component needs to display different data.

Examples:

  • User profile pages
  • Product detail pages
  • Blog articles
  • Order details
  • Category pages

Instead of creating separate routes:


/user1
/user2
/user3

developers use dynamic routing:


/user/:id

This makes applications:

  • More scalable
  • Cleaner
  • Easier to manage

Installing React Router

Before using URL parameters, install React Router.


npm install react-router-dom

Basic Setup of React Router


import {
 BrowserRouter,
 Routes,
 Route
} from "react-router-dom";

Creating URL Parameters

Example Route


<Route
 path="/product/:id"
 element={<Product />}
/>

Here:

  • :id is the parameter

Possible URLs:


/product/1
/product/5
/product/100

Accessing URL Parameters

React Router provides the useParams() hook.

Import useParams


import { useParams } from "react-router-dom";

Syntax of useParams


const params = useParams();

OR


const { id } = useParams();

Basic Example of URL Parameters

Step 1: Create Route

App.js


import {
 BrowserRouter,
 Routes,
 Route
} from "react-router-dom";
import Product from "./Product";
function App() {
 return (
   <BrowserRouter>
     <Routes>
       <Route
         path="/product/:id"
         element={<Product />}
       />
     </Routes>
   </BrowserRouter>
 );
}
export default App;

Step 2: Access Parameter

Product.js


import { useParams } from "react-router-dom";
function Product() {
 const { id } = useParams();
 return (
   <h1>Product ID: {id}</h1>
 );
}
export default Product;

Output Example

If the URL is:


/product/10

Output:

Product ID: 10

Multiple URL Parameters

React Router supports multiple parameters.

Example


<Route
 path="/user/:userId/post/:postId"
 element={<Post />}
/>

Accessing Multiple Parameters


import { useParams } from "react-router-dom";
function Post() {
 const { userId, postId } = useParams();
 return (
   <div>
     <h1>User ID: {userId}</h1>
     <h1>Post ID: {postId}</h1>
   </div>
 );
}
export default Post;

Real-Life Example: E-Commerce Website

Route


<Route
 path="/products/:id"
 element={<ProductDetails />}
/>

URL Examples


/products/1
/products/2
/products/50

Each URL displays different product data.

Fetching API Data Using URL Parameters

URL parameters are commonly used with APIs.

Example


import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
function ProductDetails() {
 const { id } = useParams();
 const [product, setProduct] = useState(null);
 useEffect(() => {
   fetch(`https://api.example.com/products/${id}`)
     .then((response) => response.json())
     .then((data) => {
       setProduct(data);
     });
 }, [id]);
 return (
   <div>
     <h1>{product?.title}</h1>
   </div>
 );
}
export default ProductDetails;

URL Parameters vs Query Parameters

URL Parameters


/product/5

Used for identifying specific resources.

Query Parameters


/products?category=mobile

Used for filtering or searching.

Comparison Table

Feature URL Parameters Query Parameters
Position Inside route path After ? symbol
Usage Specific resource Filtering/search
Example /user/5 /users?role=admin

Optional URL Parameters

React Router v6 handles optional routes differently than previous versions.

Example


<Route
 path="/profile/:id"
 element={<Profile />}
/>

You can create separate routes for optional behavior.

Nested Dynamic Routes

Nested routes also support parameters.


<Route
 path="/dashboard/:id"
 element={<Dashboard />}
>
 <Route
   path="settings"
   element={<Settings />}
 />
</Route>

Using URL Parameters with useNavigate

You can navigate dynamically.

Example

navigate(`/product/${id}`);

Advantages of URL Parameters

1. Dynamic Routing

Same component handles multiple pages.

2. Cleaner URLs

Readable and user-friendly URLs.

3. Better SEO

Meaningful URLs improve SEO.

4. Scalability

No need to create multiple static routes.

5. API Integration

Easy to fetch data dynamically.

Common Mistakes

1. Forgetting Colon :

Wrong:


path="/user/id"

Correct:


path="/user/:id"

2. Using useParams Outside Router

Wrong:


const params = useParams();
without BrowserRouter.

Correct:


const { id } = useParams();

4. Forgetting Dependency in useEffect

Wrong:


useEffect(() => {
 fetchData();
}, []);

Correct:


useEffect(() => {
 fetchData();
}, [id]);

5. Assuming Parameters are Numbers

URL parameters are always strings.

Example:


console.log(typeof id);

Output:

string

Best Practices

Use Meaningful Parameter Names

Good:


/user/:userId

Bad:


/user/:x

Validate Parameters

Check if parameters are valid before using them.

Use Dynamic Fetching Carefully

Handle loading and error states properly.

Keep URLs Clean

Good:


/products/15

Bad:


/products/details/item/15/data

Combine with SEO-Friendly URLs

Example:


/blog/react-hooks-guide

Advanced Example

Blog Article Route


<Route
 path="/blog/:slug"
 element={<BlogPost />}
/>

BlogPost Component


mport { useParams } from "react-router-dom";
function BlogPost() {
 const { slug } = useParams();
 return (
   <h1>{slug}</h1>
 );
}
export default BlogPost;

Conclusion

URL Parameters are an important feature in React Router that allows developers to create dynamic and scalable React applications.

They help applications:

  • Display dynamic content
  • Create cleaner URLs
  • Improve SEO
  • Fetch API data dynamically
  • Build scalable routing system

By mastering URL Parameters and the useParams() hook, developers can build more powerful and professional ReactJS applications.

Continue Learning React