![]()
Dynamic Nested Routing in React (React Router v6+)
In React Router v6+, dynamic nested routing allows you to define routes that can change based on dynamic parameters or nested layouts. This feature is especially useful for applications that have sections with complex, nested views or for managing routes that depend on data such as user IDs, categories, or other dynamic values.
What is Dynamic Nested Routing?
Dynamic nested routing refers to creating routes that change depending on dynamic parameters, such as:
- User IDs or other identifiers
- Category-based navigation (e.g.,
/products/:categoryId) - Nested routes that change based on a parent route’s state or parameters
Why is Dynamic Nested Routing Useful?
Dynamic nested routes are commonly used in applications with:
- Dashboard views: Where the main layout remains the same, but different content (like user profiles or settings) is loaded based on the URL.
- Product listing or categories: Where you have a main category page, and the subcategories or products are dynamically loaded.
- User or project details: Where the path reflects user-specific data and you need to display nested components based on those IDs.
Basic Setup of Dynamic Nested Routing
Here’s an example of how to implement dynamic nested routing with React Router v6:
- Basic Routing Setup
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link, useParams } from 'react-router-dom';
// Nested Routes Components
const ProductList = () => {
return (
<div>
<h2>Product List</h2>
<Link to="electronics">Electronics</Link>
<Link to="clothing">Clothing</Link>
</div>
);
};
const ProductCategory = () => {
const { categoryId } = useParams();
return <h2>Category: {categoryId}</h2>;
};
const HomePage = () => {
return (
<div>
<h1>Home Page</h1>
<Link to="/products">Go to Products</Link>
</div>
);
};
const App = () => {
return (
<Router>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="products" element={<ProductList />}>
<Route path=":categoryId" element={<ProductCategory />} />
</Route>
</Routes>
</Router>
);
};
export default App;
Explanation:
<Route path="products": Defines a base route for/products.- Nested Routes: Inside the
/productsroute, we define a dynamic nested route:categoryIdto load different product categories. - Dynamic Path with
:categoryId: The URL/products/electronicsor/products/clothingdynamically loads different content based on thecategoryIdparameter.
How It Works:
- Dynamic Parameters: When navigating to
/products/electronics, thecategoryIdin the URL will be passed to theProductCategorycomponent using theuseParamshook. - Nested Routes: React Router v6 automatically renders the correct component inside the parent route. In this case, the
ProductCategorycomponent is rendered inside theProductListcomponent when you navigate to/products/:categoryId.
Advanced Example: Nested Routing with Layouts and Dynamic Content
You can use layout components to wrap the common sections of a page (like headers or sidebars) while rendering dynamic content in nested routes.
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link, Outlet, useParams } from 'react-router-dom';
// Layout Component
const Layout = () => {
return (
<div>
<header>
<h1>My Online Store</h1>
<nav>
<Link to="/">Home</Link>
<Link to="products">Products</Link>
</nav>
</header>
<main>
<Outlet /> {/* Render nested routes here */}
</main>
</div>
);
};
// Components for Product Categories and Individual Products
const ProductList = () => {
return (
<div>
<h2>Product List</h2>
<Link to="electronics">Electronics</Link>
<Link to="clothing">Clothing</Link>
</div>
);
};
const ProductCategory = () => {
const { categoryId } = useParams();
return <h2>Category: {categoryId}</h2>;
};
const ProductDetail = () => {
const { productId } = useParams();
return <h2>Product Details for: {productId}</h2>;
};
const HomePage = () => {
return <h2>Welcome to My Online Store!</h2>;
};
// Main Application
const App = () => {
return (
<Router>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<HomePage />} />
<Route path="products" element={<ProductList />}>
<Route path=":categoryId" element={<ProductCategory />}>
<Route path=":productId" element={<ProductDetail />} />
</Route>
</Route>
</Route>
</Routes>
</Router>
);
};
export default App;
Explanation:
<Layout />: This serves as the wrapper component with the common layout for the website (like a header or navigation). It uses the<Outlet />to render nested routes dynamically.<Outlet />: This is a placeholder where the child routes will be rendered. For example, when navigating to/products/electronics/laptop, the correspondingProductCategoryandProductDetailcomponents will be rendered inside the layout.- Nested Routes: The structure allows you to handle multiple levels of nesting. In this example, there’s a dynamic path for both categories and individual product details.
How It Works in Depth:
useParams(): In bothProductCategoryandProductDetail,useParams()is used to extract dynamic parameters likecategoryIdandproductIdfrom the URL.- Nested Route Matching: React Router will automatically match and render the nested routes. For instance, if you navigate to
/products/electronics/laptop, React Router will:- Render the
ProductListcomponent from/products - Render the
ProductCategorycomponent from/products/electronics - Render the
ProductDetailcomponent from/products/electronics/laptop
- Render the
Dynamic Nested Routing Use Cases
Dynamic nested routing is very useful for apps like:
- E-commerce websites: Where you have categories, subcategories, and product pages.
- Admin dashboards: Where the structure of nested routes depends on the section, such as users, settings, reports, etc.
- Blogging platforms: Where you have categories, tags, and individual posts.
Best Practices for Dynamic Nested Routing
- Use Layouts for Reusability: Layout components help maintain consistency for the UI, especially when the structure of the app remains the same but the content changes.
- Keep Routes Logical and Simple: Avoid overly deep nesting of routes. This makes the routing structure difficult to maintain.
- Optimize for SEO: Ensure that dynamically generated URLs reflect meaningful content for SEO purposes (e.g., using category names or product names in the URL).
