Back to all posts

Nested Routes in React Router


Nested routes in React Router allow developers to create complex routing structures where certain components are rendered based on the current URL path. This feature is particularly useful for building single-page applications (SPAs) where the user interface does not need to reload the entire page when navigating between different parts of the application. In this blog, we will explore how to implement nested routes using React Router v6, focusing on the provided code snippet

Setting Up Nested Routes

To begin with, let’s understand the structure of the provided code snippet. It defines a root route (/) with a RootLayout component as its element. This root route has two child routes: a home route (/) rendering the HomePage component, and an events route (/events) with its own set of child routes.

//App.jsx
const router = createBrowserRouter([
 {
    path: '/',
    element: <RootLayout />,
    children: [
      {
        path: '/',
        element: <HomePage />,
      },
      {
        path: '/events',
        element: <EventsNavigationLayout />,
        children: [
          {
            path: '',
            element: <EventsPage />,
          },
          {
            path: ':eventId',
            element: <EventDetailPage />,
          },
          {
            path: 'new',
            element: <NewEventPage />,
          },
          {
            path: ':eventId/edit',
            element: <EditEventPage />,
          },
        ]
      },
    ]
 }
])
//RootLayout
import {Outlet} from 'react-router-dom'
import MainNavigation from '../components/MainNavigation'

function RootLayout() {
    return (
        <>
            <MainNavigation />
            <main>
                <Outlet />
            </main>
        </>
    )
}

export default RootLayout;
//EventsNavigationLayout
import { Outlet } from 'react-router-dom';
import EventsNavigation from '../components/EventsNavigation';

function EventsNavigationLayout() {
    return <>
        <EventsNavigation />
        <Outlet />
    </>
}

export default EventsNavigationLayout;

Check Complet Routing Blog: https://chethanspoojary.com/blog/building-a-multi-pages-spa-with-react-router/

Result: