๐งญ Dynamic Routing in React
Dynamic routing allows your app to handle URLs with changing values โ such as user profiles, blog posts, or product pages โ using parameters in the URL path.
๐ 1. Define a Route with Parameters
Use the :param
syntax to declare a dynamic segment in the path.
import { Routes, Route } from 'react-router-dom';
import ProductPage from './pages/ProductPage';
function App() {
return (
<Routes>
<Route path="/product/:id" element={<ProductPage />} />
</Routes>
);
}
๐งช 2. Access URL Parameters
Inside your component, use the useParams()
hook from react-router-dom
to retrieve the dynamic value.
import { useParams } from 'react-router-dom';
function ProductPage() {
const { id } = useParams();
return <h2>Product ID: {id}</h2>;
}
๐ 3. Example Routes
/user/42
โ Show user with ID 42/blog/react-hooks
โ Load a blog post by slug/product/123
โ Product page for item 123
โ๏ธ 4. Multiple Parameters
<Route path="/post/:category/:slug" element={<BlogPost />} />
const { category, slug } = useParams();
With dynamic routing, you can generate pages based on user interaction, API data, or backend content โ enabling you to build flexible, scalable UIs.