DEV Community

Md Yusuf
Md Yusuf

Posted on

Understanding Nested Routes in React: A Comprehensive Guide

In React, nested routes allow you to structure your routes hierarchically, where one route is nested inside another. This is useful when building complex UIs where certain components or pages are shared across different routes.

To create nested routes, you can use React Router, a popular library for handling routing in React applications.

Example using React Router (v6):

  1. Install React Router:
   npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode
  1. Set up nested routes:
   import { BrowserRouter as Router, Routes, Route, Outlet, Link } from 'react-router-dom';

   // Layout Component with Nested Routes
   function Layout() {
     return (
       <div>
         <nav>
           <ul>
             <li>
               <Link to="/">Home</Link>
             </li>
             <li>
               <Link to="/about">About</Link>
             </li>
             <li>
               <Link to="/dashboard">Dashboard</Link>
             </li>
           </ul>
         </nav>

         {/* This is where nested routes will be rendered */}
         <Outlet />
       </div>
     );
   }

   // Components for each route
   function Home() {
     return <h2>Home Page</h2>;
   }

   function About() {
     return <h2>About Page</h2>;
   }

   function Dashboard() {
     return (
       <div>
         <h2>Dashboard</h2>
         <nav>
           <ul>
             <li>
               <Link to="stats">Stats</Link>
             </li>
             <li>
               <Link to="settings">Settings</Link>
             </li>
           </ul>
         </nav>

         {/* Nested routes inside Dashboard */}
         <Outlet />
       </div>
     );
   }

   function Stats() {
     return <h2>Dashboard Stats</h2>;
   }

   function Settings() {
     return <h2>Dashboard Settings</h2>;
   }

   // App Component with Routes
   function App() {
     return (
       <Router>
         <Routes>
           <Route path="/" element={<Layout />}>
             <Route index element={<Home />} />
             <Route path="about" element={<About />} />
             <Route path="dashboard" element={<Dashboard />}>
               <Route path="stats" element={<Stats />} />
               <Route path="settings" element={<Settings />} />
             </Route>
           </Route>
         </Routes>
       </Router>
     );
   }

   export default App;
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • Outlet: This is where the nested route components are rendered.
  • Route path="/" element={<Layout />}: The main route with nested children.
  • Nested Route: The <Route path="dashboard" element={<Dashboard />}> contains further nested routes for "stats" and "settings."

This structure allows you to have a common layout (like a dashboard menu) and dynamically load specific sections like stats or settings based on the nested routes.

Top comments (0)