Skip to main content

Dynamic Routing

Dynamic routing is a powerful technique used in web development to handle navigation and rendering of pages based on changing parameters. Unlike traditional static routing, where pages are created and rendered component by component, dynamic routing allows for more flexible and efficient handling of complex app scenarios.

 

Thinking of e-commerce website that contain a lot of products like Shopee

1706280757083.png1706280793369.png

When you see the product and you click to see the detail of that product. Do you think Shopee creating pages for each individual product? The answer is NO!

They use dynamic routing to help.


How to implement dynamic routing in React

Like the basic navigation, you define the path and define which element should be render according to that path.

const App = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/product/:productId" element={<Product />} />
      </Routes>
    </BrowserRouter>
  );
}

But for dynamic routing as you can see on example code above /product/:productId

 /:productId  indicate that this part of the URL will be dynamic and represent the product's unique identifier.

In the Product component, we can access the productId parameter using the useParams hook provided by react-router-dom:

//Product.tsx
import { useParams } from "react-router-dom";

export default function Product() {
  const { productId } = useParams();
  return (
    <>
      <div className="main">
        <h1>Product {productId}</h1>
      </div>
    </>
  );
}

when we access URL localhost:5173/product/12332 the product number will dynamically change according to parameter productId in URL.

1706287100316.png