Saturday, 25 January 2025

Mastering Nested Routes in React: A Guide to Using createBrowserRouter for Child Routes

What are Child Routes in React?

In React, child routes refer to nested routes inside a parent route, allowing you to organize routes hierarchically. This concept is often used in applications where you need to render a parent component and then dynamically render a subcomponent (child component) based on the URL path.

 

For example, in a dashboard, the main dashboard page could be the parent route, and specific sections like "MemoryMetrics", "CpuMetrics" or "NetworkStats" would be child routes.

 

Use Case for Child Routes

Child routes are useful when,

 

1.   You want to render a component based on part of a path, but still display a shared parent component.

2.   You have a UI structure where sub-sections need to render under the main section (e.g., dashboards, profile pages).

3.   You want better organization of routes by logically nesting them, making your code more modular and maintainable.

 

For instance, consider a website with user profiles. The main /profile route might render the user's profile, while child routes like /profile/settings or /profile/orders might render specific subpages of the profile.

 

How to specify Child Routes Using children Property in React Router?

In React Router (v6 and later), child routes are specified using the children property.

// Define routes using createBrowserRouter
const router = createBrowserRouter([
  {
    path: "/dashboard",
    element: <Dashboard />,
    children: [
      {
        path: "memory-metrics",
        element: <Memorymetrics />,
      },
      {
        path: "cpu-metrics",
        element: <CpuMetrics />,
      },
      {
        path: "network-stats",
        element: <NetworkStats />,
      },
    ],
  },
]);

 

createBrowserRouter: This method allows you to define your route hierarchy, including parent-child relationships, using an array of objects.

 

Child routes: The child routes (/dashboard/memory-metrics, /dashboard/cpu-metrics and /dashboard/network-stats) are nested within the parent route /dashboard using the children array.

 

const App = () => {

  return <RouterProvider router={router} />;

};

 

RouterProvider: This component is used to provide the routing configuration to your application. You pass the router object created using createBrowserRouter to RouterProvider.

 

Dashboard component is defined like below.

 

export const Dashboard = () => {
  return (
    <div>
      <h2>Dashboard</h2>
      {/* The Outlet component will render the child routes here */}
      <Outlet />
    </div>
  );
};

The Outlet component in React Router is a placeholder that renders the matching child routes of a parent route. It allows you to define a parent layout (like a Dashboard in your case) and display child components (like Memorymetrics or CpuMetrics) based on the current nested route.

 

Routes explained

·      /dashboard: Only the Dashboard component will be rendered. The child routes (like memory-metrics, cpu-metrics, network-stats) won't be rendered since the path is just /dashboard, and no child route matches.

 

·      /dashboard/memory-metrics: The Dashboard component will be rendered, and inside the Outlet of Dashboard, the MemoryMetrics component will be displayed because this child route matches the path: "memory-metrics".

 

·      /dashboard/cpu-metrics: Similar to the previous route, the Dashboard component will be rendered. Inside the Outlet, the CpuMetrics component will be displayed because the cpu-metrics path matches the route definition.

 

Follow below step-by-step procedure to build the complete working Application.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘child-routes-demo’.

 

Project structure looks like below.


 


Step 2: Navigate to the project directory and install react router dom by executing below commands.

 

cd child-routes-demo

npm install react-router-dom

 

Step 3: Create pages folder in src folder and define Dashboard.jsx file.

 

Dashboard.jsx

 

import { Outlet } from "react-router-dom";

export const Dashboard = () => {
  return (
    <div>
      <h2>Dashboard</h2>
      {/* The Outlet component will render the child routes here */}
      <Outlet />
    </div>
  );
};

export function Memorymetrics() {
  return (
    <>
      <h3>Memory Metrics</h3>
    </>
  );
}

export function CpuMetrics() {
  return (
    <>
      <h3>CPU Metrics</h3>
    </>
  );
}

export function NetworkStats() {
  return (
    <>
      <h3>Network Statistics</h3>
    </>
  );
}

export default Dashboard;

 

Step 4: Update App.jsx file with below content.

 

App.jsx

 

import React from "react";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import {
  Dashboard,
  Memorymetrics,
  CpuMetrics,
  NetworkStats,
} from "./pages/Dashboard";

// Define routes using createBrowserRouter
const router = createBrowserRouter([
  {
    path: "/dashboard",
    element: <Dashboard />,
    children: [
      {
        path: "memory-metrics",
        element: <Memorymetrics />,
      },
      {
        path: "cpu-metrics",
        element: <CpuMetrics />,
      },
      {
        path: "network-stats",
        element: <NetworkStats />,
      },
    ],
  },
]);

const App = () => {
  return <RouterProvider router={router} />;
};

export default App;

 

Step 5: Update main.jsx with below content.

 

main.jsx

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>
);

 

Step 6: Build and run the application by executing below commands.

  cd child-routes-demo
  npm install
  npm run dev

Open the url ‘http://localhost:5173/dashboard’, you will see below screen.

 


Open the url ‘http://localhost:5173/dashboard/memory-metrics’, you will see below screen.

 


Open the url ‘http://localhost:5173/dashboard/cpu-metrics’, you will see below screen.  



Open the url ‘http://localhost:5173/dashboard/network-stats’, you will see below screen.



You can download the application from this link.

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment