Menu

React Router Nested Routes and 404 Page

Nested Routes and 404 Pages

Catch-All 404 Route

Add a route with path="*" as the last route. It matches anything no other route matched.

jsx

import { Routes, Route } from "react-router-dom";
import NotFound from "./pages/NotFound";

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/courses" element={<Courses />} />
  <Route path="/courses/:courseId" element={<CourseDetails />} />
  <Route path="*" element={<NotFound />} />
</Routes>

src/pages/NotFound.jsx

jsx

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

function NotFound() {
  return (
    <div className="not-found">
      <h1>404 — Page not found</h1>
      <p>The page you are looking for does not exist.</p>
      <Link to="/">Go to homepage</Link>
    </div>
  );
}

export default NotFound;

Nested Routes

When several pages share a layout, a dashboard with a persistent sidebar, for example, nest the routes inside a parent route.

jsx

<Routes>
  <Route path="/dashboard" element={<DashboardLayout />}>
    <Route index element={<Overview />} />
    <Route path="courses" element={<MyCourses />} />
    <Route path="profile" element={<Profile />} />
  </Route>
</Routes>

src/pages/DashboardLayout.jsx

jsx

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

function DashboardLayout() {
  return (
    <div className="dashboard">
      <aside>
        <NavLink to="/dashboard">Overview</NavLink>
        <NavLink to="/dashboard/courses">My Courses</NavLink>
        <NavLink to="/dashboard/profile">Profile</NavLink>
      </aside>

      <main>
        <Outlet />
      </main>
    </div>
  );
}

export default DashboardLayout;

How It Works

  • <Outlet /> marks where the matching child route should render. The sidebar stays put; only the <main> content changes.
  • Child paths are relative. path="courses" inside a parent at /dashboard produces /dashboard/courses. Do not write a leading slash on child routes.
  • <Route index element={<Overview />} /> is the default child, shown when the URL is exactly /dashboard.

Practice Task

Add a nested /dashboard/settings route with a settings page and a 404 route inside the dashboard that catches unknown dashboard URLs while keeping the sidebar visible.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details