Blog>
Snippets

Implementing Nested Routes for Hierarchical Page Structures

Explain how to set up nested routes to represent hierarchical relationships between components in the application.
import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Team from './components/Team';
import MemberDetail from './components/MemberDetail';
First, import React and necessary components from react-router-dom along with the component files for the respective routes.
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path='/' element={<Home />} />
        <Route path='about' element={<About />}>
          <Route path='team' element={<Team />}>
            {/* Nested route below will match `/about/team/:memberId` */}
            <Route path=':memberId' element={<MemberDetail />} />
          </Route>
        </Route>
      </Routes>
    </BrowserRouter>
  );
}
This code snippet demonstrates the setup of nested routes. A route for '/about/team' is nested inside the '/about' route, and a parameterized route for member details is nested inside the '/about/team' route, creating a hierarchical structure.