← Back to Chapters

Nested Routes

? Nested Routes

? Quick Overview

Nested routes let you render child pages inside a parent layout. They are commonly used for dashboards, profiles, and settings pages that share UI structure.

? Key Concepts

  • Parent routes define shared layout
  • Child routes render inside <Outlet />
  • Relative paths keep routes clean

? Nested Route Simulator

Click the navigation buttons to see how the Outlet changes while the Parent stays fixed.

? localhost:3000/dashboard/
Select an option above

? Syntax / Theory

React Router v6 uses nested <Route> elements combined with the <Outlet /> component.

? Code Example – Routes Setup

? View Code Example
// Defining nested routes in React Router v6
import React from "react";
import { Routes, Route } from "react-router-dom";
import Dashboard from "./pages/Dashboard";
import Profile from "./pages/Profile";
import Settings from "./pages/Settings";

function App() {
  return (
    <Routes>
      <Route path="/dashboard" element={<Dashboard />}>
        <Route path="profile" element={<Profile />} />
        <Route path="settings" element={<Settings />} />
      </Route>
    </Routes>
  );
}

export default App;

? Parent Layout with Outlet

? View Code Example
// Outlet renders the active child route
import React from "react";
import { Link, Outlet } from "react-router-dom";

function Dashboard() {
  return (
    <div>
      <h3>Dashboard</h3>
      <nav>
        <Link to="profile">Profile</Link>
        <Link to="settings">Settings</Link>
      </nav>
      <Outlet />
    </div>
  );
}

export default Dashboard;

? Child Components

? View Code Example
// Profile page component
function Profile() {
  return <h5>Welcome to your Profile</h5>;
}

export default Profile;
? View Code Example
// Settings page component
function Settings() {
  return <h5>Adjust your Settings here</h5>;
}

export default Settings;

⚙️ Index Route

? View Code Example
// Index route shows default content
<Route path="/dashboard" element={<Dashboard />}>
  <Route index element={<h5>Select an option</h5>} />
  <Route path="profile" element={<Profile />} />
  <Route path="settings" element={<Settings />} />
</Route>

? Tips & Best Practices

  • Always include <Outlet /> in parent layouts
  • Prefer relative paths for nested routes
  • Use index routes for default content

? Try It Yourself

  1. Create a dashboard layout
  2. Add profile and settings pages
  3. Navigate without reloading layout