← Back to Chapters

404 – Not Found Routes

? 404 – Not Found Routes

? Quick Overview

In React Router, a 404 – Not Found route handles URLs that don’t match any defined route. Using a special catch-all path (*), you can show a friendly fallback page instead of leaving users lost.

? Key Concepts

  • Catch-all route using path="*"
  • Dedicated NotFound component
  • Nested 404 handling in layouts
  • errorElement with createBrowserRouter

? Basic Syntax

The wildcard route must always be placed after all valid routes so it only matches unknown paths.

? View Code Example
// App.js - Defining a catch-all 404 route
import React from "react";
import { Routes, Route, Link } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
import NotFound from "./pages/NotFound";

function App() {
  return (
    <div>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>
      </nav>

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </div>
  );
}

export default App;

? NotFound Component

? View Code Example
// NotFound.js - UI shown for invalid routes
import React from "react";
import { Link } from "react-router-dom";

function NotFound() {
  return (
    <div>
      <h2>404 - Page Not Found</h2>
      <p>The page you are looking for does not exist.</p>
      <Link to="/">Go Back Home</Link>
    </div>
  );
}

export default NotFound;

? Nested Layout 404

? View Code Example
// Nested catch-all route inside a dashboard layout
<Route path="/dashboard" element={<Dashboard />}>
<Route index element={<Home />} />
<Route path="settings" element={<Settings />} />
<Route path="*" element={<NotFound />} />
</Route>

⚙️ createBrowserRouter (v6.6+)

? View Code Example
// router.js - Handling 404 using errorElement
import { createBrowserRouter } from "react-router-dom";
import App from "./App";
import NotFound from "./pages/NotFound";

const router = createBrowserRouter([
  {
    path: "/",
    element: <App />,
    errorElement: <NotFound />
  }
]);

export default router;

? Tips & Best Practices

  • Always place the * route at the end.
  • Keep the 404 page simple and friendly.
  • Provide navigation back to a safe page.
  • Prefer errorElement when using data routers.

? Try It Yourself

  1. Create a reusable NotFound component.
  2. Add a wildcard route to your app.
  3. Test invalid URLs manually.
  4. Experiment with errorElement.

Goal: Gracefully handle missing routes in every navigation flow.