reactjs
/

React Dynamic Routing – Handling Variable URLs

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

reactjs

React Dynamic Routing – Handling Variable URLs

What is Dynamic Routing?

Dynamic routing allows you to define a single route path that can match multiple URLs based on a pattern. Instead of creating a separate route for every user or product, you use placeholders (params) to capture values from the URL and use them to fetch specific data.

URL Parameters (useParams)

To define a dynamic segment, you prefix the path part with a colon :. React Router will then capture whatever value is in that position and make it available via the useParams hook.

React JSXRead-only
1
// 1. Define the Route in App.js
<Route path="/product/:productId" element={<ProductDetail />} />

// 2. Access the ID in the Component
import { useParams } from 'react-router-dom';

function ProductDetail() {
  const { productId } = useParams();
  
  // Use productId to fetch data from an API
  return <h2>Showing details for product # {productId}</h2>;
}

Query Strings (useSearchParams)

Query strings are the key-value pairs at the end of a URL (e.g., /search?query=react&sort=asc). Unlike path params, these are optional and handled via the useSearchParams hook, which works similarly to useState.

React JSXRead-only
1
import { useSearchParams } from 'react-router-dom';

function SearchPage() {
  const [searchParams, setSearchParams] = useSearchParams();
  const query = searchParams.get('query');

  return (
    <div>
      <h3>Searching for: {query}</h3>
      <button onClick={() => setSearchParams({ query: 'flutter' })}>
        Search Flutter instead
      </button>
    </div>
  );
}

Use Cases for Dynamic Routing

  • User Profiles: /profile/:username matches /profile/kishore and /profile/john.
  • E-commerce: /category/:cid/product/:pid for deeply nested resource matching.
  • Pagination: /blog/page/:pageNumber for clean, shareable list views.
  • Filtering: Using query strings for sort order, price ranges, and search filters.

Comparison: Params vs. Search Query

FeatureURL Parameters (:id)Search Params (?q=)
RequirementRequired for the route to matchOptional/Flexible
StructurePart of the path (/user/123)Appended at end (?id=123)
Best ForIdentifying a specific resourceFiltering, sorting, searching
HookuseParams()useSearchParams()

Try it yourself

import React from 'react';
import { BrowserRouter, Routes, Route, Link, useParams, useSearchParams } from 'react-router-dom';

const Product = () => {
  const { id } = useParams();
  return <div style={{color: 'blue'}}>📦 Loading Product ID: {id}</div>;
};

const Search = () => {
  const [search] = useSearchParams();
  const term = search.get('term');
  return <div>🔍 Filtered by: {term || 'Nothing yet'}</div>;
};

export default function App() {
  return (
    <BrowserRouter>
      <div style={{ padding: '20px' }}>
        <h4>Dynamic Navigation</h4>
        <ul style={{ display: 'flex', gap: '10px', listStyle: 'none', padding: 0 }}>
          <li><Link to="/product/101">Laptop</Link></li>
          <li><Link to="/product/202">Phone</Link></li>
          <li><Link to="/search?term=react">Search React</Link></li>
        </ul>
        
        <div style={{ marginTop: '20px', borderTop: '1px solid #eee', paddingTop: '10px' }}>
          <Routes>
            <Route path="/product/:id" element={<Product />} />
            <Route path="/search" element={<Search />} />
          </Routes>
        </div>
      </div>
    </BrowserRouter>
  );
}

Test Your Knowledge

Q1
of 2

Which character is used in a route path to define a dynamic parameter?

A
?
B
#
C
:
D
*
Q2
of 2

How do you access the value of a dynamic segment in your component?

A
props.match
B
useParams()
C
useLocation()
D
window.location

Frequently Asked Questions

What happens if a user visits /product/ without an ID?

If the route is defined as /product/:id, it will NOT match. You would need to define a separate route for /product or use optional parameters if supported by your router version.

Can I have multiple dynamic segments?

Yes. You can define routes like /authors/:authorId/posts/:postId and destructure both from useParams.

Previous

react routing

Next

react api calls

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.