JavaScript and React course Β· Module 6: React Router
Nested Routes in Intergalactic Navigation
In this lesson9
On our cosmic journey through the world of React Router, it's time to delve into the concept of nested routes. Just as in real outer space, where we have galaxies containing solar systems, which in turn contain planets with their moons - in React applications we can create hierarchical navigation structures.
What are Nested Routes?
Nested routes are a technique for organizing routing in an application where some routes (components) contain other routes (components) within themselves. This allows for creating more intuitive, hierarchical navigation structures that reflect the logical layout of the application.
Nested routes are particularly useful in larger applications where there are many subsections with their own views.
Implementing Nested Routes in React Router
In React Router v6, nested routes are implemented by placing Route components inside other Route components and using the Outlet component to specify where sub-route components should be rendered.
Basic Structure of Nested Routes
import { BrowserRouter, Routes, Route, Outlet } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="galaxies" element={<GalaxiesList />} />
<Route path="galaxies/:galaxyId" element={<GalaxyLayout />}>
<Route index element={<GalaxyOverview />} />
<Route path="systems" element={<SolarSystemsList />} />
<Route path="systems/:systemId" element={<SolarSystemDetail />} />
</Route>
</Route>
</Routes>
</BrowserRouter>
);
}In the example above:
Layoutis the main component that will contain all nested viewsGalaxyLayoutis the component that will serve as a "container" for galaxy details- The
indexattribute specifies what should be rendered when the URL matches exactly the parent path
The Outlet Component
The key element of nested routes is the Outlet component, which acts as a "placeholder" for child components. It specifies where in the parent component the child route components should be rendered:
import { Outlet, Link } from 'react-router-dom';
function Layout() {
return (
<div className="app-layout">
<header>
<h1>Cosmic Atlas</h1>
<nav>
<Link to="/">Home</Link>
<Link to="/galaxies">Galaxies</Link>
</nav>
</header>
<main>
{/* Sub-route components will be rendered here */}
<Outlet />
</main>
<footer>© 2150 Intergalactic Navigation Center</footer>
</div>
);
}
function GalaxyLayout() {
const { galaxyId } = useParams();
return (
<div className="galaxy-layout">
<h2>Galaxy: {galaxyId}</h2>
<nav className="galaxy-navigation">
<Link to={`/galaxies/${galaxyId}`}>Overview</Link>
<Link to={`/galaxies/${galaxyId}/systems`}>Solar Systems</Link>
</nav>
<div className="galaxy-content">
{/* Galaxy sub-route components will be rendered here */}
<Outlet />
</div>
</div>
);
}Relative and Index Routes
React Router v6 introduced several useful features for better handling of nested routes:
1. Index Routes
An index route specifies what should be rendered when the URL matches exactly the parent path:
<Route path="galaxies" element={<GalaxiesLayout />}>
{/* This will be rendered for /galaxies */}
<Route index element={<GalaxiesList />} />
{/* This will be rendered for /galaxies/:galaxyId */}
<Route path=":galaxyId" element={<GalaxyDetails />} />
</Route>2. Relative Links
In nested components, we can use relative links that are resolved relative to the current path:
import { Link, useParams } from 'react-router-dom';
function GalaxySystemsList() {
const { galaxyId } = useParams();
return (
<div>
<h3>Solar systems in galaxy {galaxyId}</h3>
<ul>
{systems.map(system => (
<li key={system.id}>
{/* Relative link - will be resolved to /galaxies/:galaxyId/systems/:systemId */}
<Link to={system.id}>{system.name}</Link>
</li>
))}
</ul>
{/* Relative link "up" - go back one level */}
<Link to="..">Return to galaxy overview</Link>
</div>
);
}Passing Context Between Nesting Levels
One of the challenges when working with nested routes is passing data between different nesting levels. React Router v6 offers several solutions:
1. useOutletContext and useOutlet Hooks
The useOutletContext hook allows passing data from a parent component to a child:
import { Outlet, useOutletContext, useParams } from 'react-router-dom';
function GalaxyLayout() {
const { galaxyId } = useParams();
const [galaxy, setGalaxy] = useState(null);
useEffect(() => {
// Fetch galaxy data
fetchGalaxy(galaxyId).then(data => setGalaxy(data));
}, [galaxyId]);
// Pass galaxy data to child components
return (
<div className="galaxy-layout">
<h2>{galaxy?.name || 'Loading...'}</h2>
<Outlet context={{ galaxy, updateGalaxy: setGalaxy }} />
</div>
);
}
function GalaxyOverview() {
// Receive context from the parent component
const { galaxy, updateGalaxy } = useOutletContext();
if (!galaxy) return <div>Loading galaxy data...</div>;
return (
<div className="galaxy-overview">
<h3>Overview of galaxy {galaxy.name}</h3>
<p>Type: {galaxy.type}</p>
<p>Number of systems: {galaxy.systemsCount}</p>
{/* Rest of the component */}
</div>
);
}2. Shared State with React Context
For more complex scenarios, React Context can be used to share state between components:
import { createContext, useContext, useState } from 'react';
import { Outlet } from 'react-router-dom';
// Create context
const GalaxyContext = createContext();
// Hook for easy context access
function useGalaxy() {
return useContext(GalaxyContext);
}
function GalaxyProvider({ children }) {
const [selectedGalaxy, setSelectedGalaxy] = useState(null);
const [favoritesSystems, setFavoriteSystems] = useState([]);
const addFavoriteSystem = (system) => {
setFavoriteSystems(prev => [...prev, system]);
};
// Context value
const value = {
selectedGalaxy,
setSelectedGalaxy,
favoritesSystems,
addFavoriteSystem
};
return (
<GalaxyContext.Provider value={value}>
{children}
</GalaxyContext.Provider>
);
}
function GalaxiesRoot() {
return (
<GalaxyProvider>
<div className="galaxies-section">
<h2>Galaxy Exploration</h2>
<Outlet />
</div>
</GalaxyProvider>
);
}
// Usage in a child component
function SolarSystemDetail() {
const { favoritesSystems, addFavoriteSystem } = useGalaxy();
const { systemId } = useParams();
// Rest of the component
}Advanced Nesting Patterns
Nested routes can be used to implement various navigation patterns:
1. Multi-level Layout
<Routes>
<Route path="/" element={<MainLayout />}>
<Route element={<AuthLayout />}>
<Route path="dashboard" element={<Dashboard />} />
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<SettingsLayout />}>
<Route path="account" element={<AccountSettings />} />
<Route path="notifications" element={<NotificationSettings />} />
</Route>
</Route>
<Route path="about" element={<About />} />
<Route path="contact" element={<Contact />} />
</Route>
</Routes>In this example:
MainLayoutcontains the general page structureAuthLayouthandles authentication for protected pathsSettingsLayoutcreates an additional navigation level for settings
2. Dynamic Segments and Nesting
<Routes>
<Route path="galaxies" element={<GalaxiesList />} />
<Route path="galaxies/:galaxyId" element={<GalaxyLayout />}>
<Route index element={<GalaxyOverview />} />
<Route path="systems" element={<SystemsList />} />
<Route path="systems/:systemId" element={<SystemLayout />}>
<Route index element={<SystemOverview />} />
<Route path="planets" element={<PlanetsList />} />
<Route path="planets/:planetId" element={<PlanetDetails />} />
</Route>
</Route>
</Routes>This structure creates deep nesting of routes that reflects the hierarchy galaxy > solar system > planet.
3. Multiple Slots in One Layout
The galaxy control panel has three zones: navigation on the left, the main view in the middle and telemetry on the right. If you know Angular's named router-outlet or Vue Router's named views, you might look for something similar in React Router. There are no named outlets here: Outlet accepts only one prop, context, and renders the component of the matching child route (or nothing if no child route matches). If you wrote <Outlet name="sidebar" />, React Router would ignore the unknown prop and render the same child route in that spot as the main Outlet.
Instead of named slots, the layout has one Outlet for the main view, and regular components fill the other zones:
import { Outlet } from 'react-router-dom';
function DashboardLayout() {
return (
<div className="dashboard">
<aside className="sidebar">
{/* A regular sidebar navigation component */}
<MissionSidebar />
</aside>
<div className="main-content">
{/* The only Outlet: the matching child route goes here */}
<Outlet />
</div>
<aside className="auxiliary-panel">
{/* A regular auxiliary panel component */}
<AuxiliaryPanel />
</aside>
</div>
);
}The three-zone layout has not changed; only what fills the zones has. The middle depends on the address, while the side panels always render and decide for themselves what to show.
Let's assume DashboardLayout is the element of the galaxies/:galaxyId route from the earlier examples. A side panel can then read the address with hooks: useParams, which you already know, and useLocation, which returns an object describing the current address, including the path in its pathname field. You will learn more about useLocation in the upcoming lessons.
import { useLocation, useParams } from 'react-router-dom';
function AuxiliaryPanel() {
const { galaxyId } = useParams();
const { pathname } = useLocation();
return (
<div>
<h3>Galaxy telemetry: {galaxyId}</h3>
<p>Current view: {pathname}</p>
</div>
);
}At /galaxies/andromeda/systems the panel shows a heading with the andromeda identifier and the full path. The panel itself knows nothing about the child routes: it only reads its own route's params and the address.
Sometimes it is the child route that should decide what appears in the panel. That is what the route handle property is for: any data a route attaches to its match. You read it with the useMatches() hook, which returns all active matches, from the layout down to the deepest child route. The React Router documentation shows this pattern for breadcrumbs. There is one condition: useMatches works only in a data router, that is, when you pass your routes to createBrowserRouter and render the app with <RouterProvider router={router} />. Such a router knows the whole route tree up front. Inside <BrowserRouter> the hook throws an error.
import { createBrowserRouter } from 'react-router-dom';
const router = createBrowserRouter([
{
path: '/galaxies/:galaxyId',
element: <DashboardLayout />,
children: [
{ index: true, element: <GalaxyOverview /> },
{
path: 'systems',
element: <SystemsList />,
// handle: any data attached to this route's match
handle: { sidebar: () => <SystemsFilter /> },
},
],
},
]);Here the routes are described by an array of objects instead of <Route> components, but the structure is the same: a layout with its child routes in children, and index: true plays the role of the index attribute. The only new part is the handle property on the systems route: its sidebar field is a function that returns the panel. Now MissionSidebar goes through the matches starting from the deepest one and uses the first handle.sidebar it finds:
import { useMatches } from 'react-router-dom';
function MissionSidebar() {
const matches = useMatches();
const match = [...matches].reverse().find((m) => m.handle?.sidebar);
return match ? match.handle.sidebar() : <p>Choose a solar system</p>;
}The copy of the array ([...matches]) is needed because reverse() reverses an array in place. At /galaxies/andromeda/systems the left panel shows SystemsFilter, because the systems route decided so. At /galaxies/andromeda the index route has no handle, so the panel displays the default text, and the layout keeps exactly one Outlet the whole time. I recommend starting with regular components that use useParams and useLocation, and reaching for handle only when each child route needs its own content in the panel. You will meet the data router again when blocking navigation, in the lesson about browser history.
Optimizing Nested Routes
When working with nested routes, it's worth keeping a few optimization techniques in mind:
1. Lazy Loading Components
For improved performance, components can be loaded dynamically only when they are needed:
import { Suspense, lazy } from 'react';
import { Routes, Route } from 'react-router-dom';
// Lazy loading components
const GalaxyLayout = lazy(() => import('./GalaxyLayout'));
const GalaxiesList = lazy(() => import('./GalaxiesList'));
const SolarSystemDetails = lazy(() => import('./SolarSystemDetails'));
function App() {
return (
<Routes>
<Route path="/" element={<MainLayout />}>
{/* Lazily loaded component */}
<Route
path="galaxies"
element={
<Suspense fallback={<div>Loading galaxies...</div>}>
<GalaxiesList />
</Suspense>
}
/>
<Route
path="galaxies/:galaxyId/*"
element={
<Suspense fallback={<div>Loading galaxy data...</div>}>
<GalaxyLayout />
</Suspense>
}
/>
</Route>
</Routes>
);
}2. Render Optimization
Render optimization can be especially important with deep nesting, when a URL parameter change at a deep level can cause unnecessary re-rendering of higher-level components:
import { memo } from 'react';
import { Outlet, useParams } from 'react-router-dom';
// Optimized component - won't re-render if its props don't change
const MemoizedGalaxyLayout = memo(function GalaxyLayout() {
const { galaxyId } = useParams();
console.log(`Rendering GalaxyLayout for galaxy ${galaxyId}`);
return (
<div className="galaxy-layout">
<h2>Galaxy: {galaxyId}</h2>
<Outlet />
</div>
);
});Complete Application Example with Nested Routes
Below is an example of a complete space application with nested routes:
import React from 'react';
import {
BrowserRouter,
Routes,
Route,
Outlet,
Link,
NavLink,
useParams,
useOutletContext,
useNavigate
} from 'react-router-dom';
// Main application layout
function AppLayout() {
return (
<div className="cosmos-explorer">
<header className="main-header">
<h1>Cosmic Traveler's Atlas</h1>
<MainNavigation />
</header>
<main className="main-content">
<Outlet />
</main>
<footer className="main-footer">
<p>© 2150 Intergalactic Travel Agency</p>
</footer>
</div>
);
}
// Main navigation
function MainNavigation() {
return (
<nav className="main-nav">
<ul>
<li><NavLink to="/" end>Command Center</NavLink></li>
<li><NavLink to="/galaxies">Galaxies</NavLink></li>
<li><NavLink to="/missions">Missions</NavLink></li>
<li><NavLink to="/crew">Crew</NavLink></li>
</ul>
</nav>
);
}
// Home page
function Dashboard() {
return (
<div className="dashboard">
<h2>Spaceship Command Center</h2>
<p>Welcome, Captain! Which location would you like to explore today?</p>
<div className="dashboard-tiles">
<div className="tile">
<h3>Galaxies</h3>
<p>Explore different galaxies in the universe</p>
<Link to="/galaxies" className="tile-link">Go to galaxies</Link>
</div>
<div className="tile">
<h3>Missions</h3>
<p>Browse current and future space missions</p>
<Link to="/missions" className="tile-link">Go to missions</Link>
</div>
<div className="tile">
<h3>Crew</h3>
<p>Manage spaceship crew members</p>
<Link to="/crew" className="tile-link">Go to crew</Link>
</div>
</div>
</div>
);
}
// ===== GALAXIES SECTION =====
// Galaxies layout
function GalaxiesLayout() {
return (
<div className="galaxies-section">
<h2>Galaxy Exploration</h2>
<Outlet />
</div>
);
}
// Galaxies list
function GalaxiesList() {
const galaxies = [
{ id: 'milky-way', name: 'Milky Way', type: 'Spiral' },
{ id: 'andromeda', name: 'Andromeda', type: 'Spiral' },
{ id: 'triangulum', name: 'Triangulum Galaxy', type: 'Spiral' },
{ id: 'large-magellanic', name: 'Large Magellanic Cloud', type: 'Irregular' }
];
return (
<div className="galaxies-list">
<h3>Available Galaxies</h3>
<div className="galaxy-cards">
{galaxies.map(galaxy => (
<div key={galaxy.id} className="galaxy-card">
<h4>{galaxy.name}</h4>
<p>Type: {galaxy.type}</p>
<Link to={galaxy.id} className="galaxy-link">
Explore galaxy
</Link>
</div>
))}
</div>
</div>
);
}
// Galaxy details layout
function GalaxyLayout() {
const { galaxyId } = useParams();
const navigate = useNavigate();
// Galaxy data simulation (in a real application fetched from API)
const galaxyData = {
'milky-way': {
name: 'Milky Way',
type: 'Spiral',
diameter: '100,000 light-years',
stars: '200-400 billion',
systems: [
{ id: 'solar', name: 'Solar System' },
{ id: 'alpha-centauri', name: 'Alpha Centauri' },
{ id: 'sirius', name: 'Sirius' }
]
},
'andromeda': {
name: 'Andromeda',
type: 'Spiral',
diameter: '220,000 light-years',
stars: '1 trillion',
systems: [
{ id: 'system-1', name: 'System M31-A' },
{ id: 'system-2', name: 'System M31-B' }
]
},
'triangulum': {
name: 'Triangulum Galaxy',
type: 'Spiral',
diameter: '60,000 light-years',
stars: '40 billion',
systems: [
{ id: 'system-1', name: 'System T1' }
]
},
'large-magellanic': {
name: 'Large Magellanic Cloud',
type: 'Irregular',
diameter: '14,000 light-years',
stars: '30 billion',
systems: []
}
};
const galaxy = galaxyData[galaxyId];
if (!galaxy) {
return (
<div className="galaxy-not-found">
<h3>Galaxy Not Found</h3>
<p>No galaxy found with identifier: {galaxyId}</p>
<button onClick={() => navigate('/galaxies')}>
Return to galaxy list
</button>
</div>
);
}
return (
<div className="galaxy-details">
<h3>Galaxy: {galaxy.name}</h3>
<nav className="galaxy-nav">
<NavLink to="" end>Overview</NavLink>
<NavLink to="systems">Solar Systems</NavLink>
<NavLink to="map">Galaxy Map</NavLink>
</nav>
<div className="galaxy-content">
<Outlet context={{ galaxy }} />
</div>
<div className="back-navigation">
<Link to="/galaxies">← Return to galaxy list</Link>
</div>
</div>
);
}
// Galaxy overview (default view)
function GalaxyOverview() {
const { galaxy } = useOutletContext();
return (
<div className="galaxy-overview">
<h4>Overview: {galaxy.name}</h4>
<table className="galaxy-stats">
<tbody>
<tr>
<th>Type:</th>
<td>{galaxy.type}</td>
</tr>
<tr>
<th>Diameter:</th>
<td>{galaxy.diameter}</td>
</tr>
<tr>
<th>Number of stars:</th>
<td>{galaxy.stars}</td>
</tr>
<tr>
<th>Discovered systems:</th>
<td>{galaxy.systems.length}</td>
</tr>
</tbody>
</table>
<h5>Fun Facts</h5>
<p>Unique fun facts about galaxy {galaxy.name} will appear here...</p>
</div>
);
}
// Solar systems list in galaxy
function GalaxySystems() {
const { galaxy } = useOutletContext();
const { galaxyId } = useParams();
return (
<div className="galaxy-systems">
<h4>Solar Systems in {galaxy.name}</h4>
{galaxy.systems.length > 0 ? (
<ul className="systems-list">
{galaxy.systems.map(system => (
<li key={system.id} className="system-item">
<div className="system-info">
<h5>{system.name}</h5>
</div>
<Link to={`/galaxies/${galaxyId}/systems/${system.id}`}>
Explore system
</Link>
</li>
))}
</ul>
) : (
<p>No systems have been discovered in this galaxy yet.</p>
)}
</div>
);
}
// Galaxy map
function GalaxyMap() {
const { galaxy } = useOutletContext();
return (
<div className="galaxy-map">
<h4>Galaxy Map: {galaxy.name}</h4>
<div className="map-placeholder">
<p>An interactive map of galaxy {galaxy.name} will appear here.</p>
<p>Currently under development...</p>
</div>
</div>
);
}
// ===== SOLAR SYSTEMS SECTION =====
// Solar system details
function SolarSystemDetails() {
const { galaxyId, systemId } = useParams();
const navigate = useNavigate();
// In a real application, data would be fetched based on galaxyId and systemId
const systemData = {
'solar': {
name: 'Solar System',
star: 'Sun',
planets: 8,
age: '4.6 billion years'
},
'alpha-centauri': {
name: 'Alpha Centauri',
star: 'Alpha Centauri A and B, Proxima Centauri',
planets: 3,
age: '4.85 billion years'
},
'sirius': {
name: 'Sirius',
star: 'Sirius A and B',
planets: 0,
age: '230 million years'
},
'system-1': {
name: 'System M31-A',
star: 'Star M31-A',
planets: 5,
age: '2.3 billion years'
},
'system-2': {
name: 'System M31-B',
star: 'Star M31-B',
planets: 7,
age: '3.1 billion years'
}
};
const system = systemData[systemId];
if (!system) {
return (
<div className="system-not-found">
<h4>System Not Found</h4>
<p>No solar system found with identifier: {systemId}</p>
<button onClick={() => navigate(`/galaxies/${galaxyId}/systems`)}>
Return to systems list
</button>
</div>
);
}
return (
<div className="system-details">
<h4>Solar System: {system.name}</h4>
<table className="system-stats">
<tbody>
<tr>
<th>Star(s):</th>
<td>{system.star}</td>
</tr>
<tr>
<th>Number of planets:</th>
<td>{system.planets}</td>
</tr>
<tr>
<th>Age:</th>
<td>{system.age}</td>
</tr>
</tbody>
</table>
<div className="back-navigation">
<Link to={`/galaxies/${galaxyId}/systems`}>
← Return to solar systems
</Link>
</div>
</div>
);
}
// ===== MISSIONS SECTION =====
// Missions layout
function MissionsLayout() {
return (
<div className="missions-section">
<h2>Space Missions</h2>
<Outlet />
</div>
);
}
// Missions list
function MissionsList() {
const missions = [
{ id: 'apollo', name: 'Apollo', status: 'Completed' },
{ id: 'artemis', name: 'Artemis', status: 'In Progress' },
{ id: 'mars-2030', name: 'Mars 2030', status: 'Planned' }
];
return (
<div className="missions-list">
<h3>Space Missions</h3>
<ul>
{missions.map(mission => (
<li key={mission.id}>
<Link to={mission.id}>{mission.name}</Link> - {mission.status}
</li>
))}
</ul>
</div>
);
}
// Mission details
function MissionDetails() {
const { missionId } = useParams();
return (
<div className="mission-details">
<h3>Mission details: {missionId}</h3>
<p>Details for mission {missionId} will appear here...</p>
<Link to="/missions">← Return to missions list</Link>
</div>
);
}
// ===== CREW SECTION =====
// Crew layout
function CrewLayout() {
return (
<div className="crew-section">
<h2>Crew Management</h2>
<Outlet />
</div>
);
}
// Crew members list
function CrewList() {
const crewMembers = [
{ id: 'crew1', name: 'John Smith', role: 'Captain' },
{ id: 'crew2', name: 'Anna Johnson', role: 'Navigator' },
{ id: 'crew3', name: 'Peter Williams', role: 'Engineer' }
];
return (
<div className="crew-list">
<h3>Crew Members</h3>
<ul>
{crewMembers.map(member => (
<li key={member.id}>
<Link to={member.id}>{member.name}</Link> - {member.role}
</li>
))}
</ul>
</div>
);
}
// Crew member details
function CrewMemberDetails() {
const { crewId } = useParams();
return (
<div className="crew-member-details">
<h3>Crew member profile: {crewId}</h3>
<p>Profile for crew member {crewId} will appear here...</p>
<Link to="/crew">← Return to crew list</Link>
</div>
);
}
// ===== MAIN APPLICATION COMPONENT =====
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<AppLayout />}>
{/* Home page */}
<Route index element={<Dashboard />} />
{/* Galaxies section */}
<Route path="galaxies" element={<GalaxiesLayout />}>
<Route index element={<GalaxiesList />} />
<Route path=":galaxyId" element={<GalaxyLayout />}>
<Route index element={<GalaxyOverview />} />
<Route path="systems" element={<GalaxySystems />} />
<Route path="map" element={<GalaxyMap />} />
</Route>
<Route path=":galaxyId/systems/:systemId" element={<SolarSystemDetails />} />
</Route>
{/* Missions section */}
<Route path="missions" element={<MissionsLayout />}>
<Route index element={<MissionsList />} />
<Route path=":missionId" element={<MissionDetails />} />
</Route>
{/* Crew section */}
<Route path="crew" element={<CrewLayout />}>
<Route index element={<CrewList />} />
<Route path=":crewId" element={<CrewMemberDetails />} />
</Route>
{/* 404 handling */}
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
</BrowserRouter>
);
}
// Component for non-existent paths
function NotFound() {
return (
<div className="not-found">
<h2>404 - Lost in Space</h2>
<p>This path does not lead to any known destination in space.</p>
<Link to="/">Return to Command Center</Link>
</div>
);
}
export default App;Best Practices for Nested Routes
- Maintain a Logical Hierarchy - The structure of nested routes should reflect the logical organization of the application
- Use Layout Components - Create dedicated layout components for each nesting level
- Optimize Data Passing - Use useOutletContext or React Context for efficient data passing
- Ensure Intuitive Navigation - Always add links that allow easy navigation up and down the hierarchy
- Split Code - Use lazy loading for performance optimization, especially for deeply nested components
- Keep URLs Clean - Design URLs to be readable and logical for the user
- Avoid Too Deep Nesting - Try not to exceed 3-4 nesting levels for clarity
Summary
Nested routes in React Router are a powerful technique for organizing navigation in React applications, allowing for the creation of intuitive, hierarchical user interface structures. Key benefits:
- Logical Organization - Routing structure reflects the logical application hierarchy
- Layout Reuse - Common UI elements can be shared between sub-routes
- Better UX - Users can easily orient themselves in the application structure
- Easier State Management - State can be stored at the appropriate nesting level
Just as in real space exploration, where we travel from a galaxy, through solar systems, to planets and moons - nested routes allow creating intuitive navigation systems that guide the user through different levels of our space application.
Code for this lesson: App.jsx
import React, { useState } from 'react';
import { BrowserRouter, Routes, Route, Link, useNavigate, useLocation } from 'react-router-dom';
// Login page
function LoginPage() {
const [username, setUsername] = useState('');
const navigate = useNavigate();
const handleLogin = (e) => {
e.preventDefault();
if (username.trim()) {
// Programmatic navigation with state passed
navigate('/dashboard', { state: { username } });
}
};
return (
<div className="page login">
<h1>Login Panel</h1>
<form onSubmit={handleLogin}>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Enter username"
/>
<button type="submit">Log in</button>
</form>
</div>
);
}
// Dashboard - using useLocation to read state
function Dashboard() {
const location = useLocation();
const navigate = useNavigate();
const username = location.state?.username || 'Guest';
const handleLogout = () => {
// Navigation with replace: true - doesn't add to history
navigate('/', { replace: true });
};
const goToMission = (missionId) => {
navigate(`/mission/${missionId}`);
};
return (
<div className="page dashboard">
<h1>Welcome, {username}!</h1>
<p>Your space mission control panel</p>
<div className="missions">
<h2>Available missions:</h2>
<div className="mission-buttons">
<button onClick={() => goToMission('apollo')}>Apollo</button>
<button onClick={() => goToMission('artemis')}>Artemis</button>
<button onClick={() => goToMission('voyager')}>Voyager</button>
</div>
</div>
<div className="navigation-demo">
<h2>Programmatic navigation:</h2>
<button onClick={() => navigate(-1)}>β Back (go -1)</button>
<button onClick={() => navigate(1)}>Forward (go 1) β</button>
<button onClick={handleLogout} className="logout">Log out</button>
</div>
</div>
);
}
// Mission page
function MissionPage() {
const navigate = useNavigate();
const location = useLocation();
// Get mission ID from URL
const missionId = location.pathname.split('/').pop();
return (
<div className="page mission">
<h1>Mission: {missionId.toUpperCase()}</h1>
<p>Mission details {missionId}</p>
<div className="location-info">
<h3>Location information:</h3>
<pre>{JSON.stringify(location, null, 2)}</pre>
</div>
<button onClick={() => navigate('/dashboard', { state: location.state })}>
β Back to panel
</button>
</div>
);
}
function App() {
return (
<BrowserRouter>
<div className="app">
<nav>
<Link to="/">Login</Link>
<Link to="/dashboard">Dashboard</Link>
</nav>
<Routes>
<Route path="/" element={<LoginPage />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/mission/:id" element={<MissionPage />} />
</Routes>
</div>
</BrowserRouter>
);
}
export default App;Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. The useParams hook allows you to:
2. The useSearchParams hook is used for:
Hands-on tasks in the game
- Code editor
Nested routes with Outlet
- Horizontal ordering
Arrange the useParams destructuring elements from left to right:
- Code editor
Search params and filtering
- Vertical ordering
Arrange the steps for configuring nested routes: