404 Pages in React with react-router-dom

When building a React application, handling unknown routes is a vital part of ensuring a smooth user experience. If a user visits a route that doesn’t exist, you want to show a helpful 404 page instead of leaving them with a blank screen or a cryptic error. In React apps that use react-router-dom, creating a 404 or “Not Found” page is straightforward—but it’s important to do it correctly.

In this detailed guide, we’ll explore how to set up and manage 404 pages in a React app using react-router-dom, including both basic and advanced techniques.


What is a 404 Page?

A 404 page is a fallback route shown when a user visits a URL that doesn’t match any defined routes in your app. It serves two main purposes:

  1. User Guidance: Let the user know that the page doesn’t exist.
  2. Navigation: Provide a way to go back or explore the site further.

Without a 404 page, users may encounter confusing behavior, or worse, they might think your app is broken.


Getting Started with react-router-dom

Before creating a 404 page, ensure you have react-router-dom installed:

npm install react-router-dom

We’ll be using React Router v6, which provides a cleaner and more powerful API than previous versions.

In your main file (e.g., App.jsx or App.tsx), set up the router structure:

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

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </BrowserRouter>
  )
}

The key part is the path="*" route—this acts as a catch-all for any route that doesn’t match the ones above it. That’s where your 404 page goes.


Creating the NotFound Component

Create a new file called NotFound.jsx or NotFound.tsx:

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

export default function NotFound() {
  return (
    <div style={{ padding: "2rem", textAlign: "center" }}>
      <h1>404 - Page Not Found</h1>
      <p>The page you are looking for does not exist.</p>
      <Link to="/">Go back to Home</Link>
    </div>
  )
}

This is a simple and clean implementation. You can customize it further by adding animations, images, or even a search bar to help users find what they’re looking for.


Understanding path=”*”

The "*" route path matches any URL that wasn’t previously matched. React Router processes routes in order from top to bottom, so the wildcard route should always be placed at the end. Otherwise, it may catch routes that are actually valid.

In React Router v6, the routing system is declarative and flat, which makes path="*" an effective and intuitive way to define fallback routes.


Adding 404 Pages in Nested Routes

If your application has nested routing, such as a dashboard layout or admin section, you can add scoped 404s inside nested routes.

Example:

<Route path="/dashboard" element={<DashboardLayout />}>
  <Route index element={<DashboardHome />} />
  <Route path="settings" element={<Settings />} />
  <Route path="*" element={<DashboardNotFound />} />
</Route>

In this case, if a user visits /dashboard/random, they’ll see the DashboardNotFound page instead of the global 404. This allows for context-specific 404 pages.


Redirecting Instead of Displaying a 404

Sometimes, instead of showing a 404, you may want to redirect users to the homepage or a different part of the app.

You can do this using the <Navigate /> component:

import { Navigate } from "react-router-dom"

function NotFoundRedirect() {
  return <Navigate to="/" replace />
}

This automatically navigates users to / if the route is not found.

However, use this sparingly. A 404 page is often more helpful than an unexpected redirect, especially when users click old or broken links.


Styling and Enhancing Your 404 Page

A good 404 page should reflect your brand’s tone and style. Some enhancements you can add:

  • Friendly message or humor
  • A search bar to help users find content
  • Helpful links to popular pages
  • Animation or custom illustrations (e.g., Lottie or SVG)
  • Dark mode compatibility
  • Analytics tracking to monitor how often 404s happen

Example with some visual flair:

export default function NotFound() {
  return (
    <div style={{ padding: "4rem", textAlign: "center", background: "#f4f4f4" }}>
      <h1 style={{ fontSize: "4rem", marginBottom: "1rem" }}>😕 404</h1>
      <p>This page doesn’t exist or has been moved.</p>
      <Link to="/" style={{ color: "#007bff", textDecoration: "underline" }}>
        Go back to Home
      </Link>
    </div>
  )
}

Deploying 404s on Static Hosts (Bonus Tip)

If you’re deploying your React app to a static hosting service like GitHub Pages or Netlify, make sure to configure your server to route all requests to index.html (for SPAs).

On Netlify, add a _redirects file with:

/*  /index.html  200

On Vercel, this is handled automatically. But check your vercel.json for rewrites if needed.

Otherwise, your users might see the server’s 404 page instead of your React one.


Conclusion

Creating a 404 page in React using react-router-dom is easy, but incredibly important for delivering a polished and helpful user experience. Whether you go for a simple text-based fallback or a fully branded error screen, catching unknown routes gracefully shows users that you care about their journey through your app.

Use path="*" as a fallback route, design it thoughtfully, and consider adding contextual 404s for nested routes when needed. A small touch like this can make a big difference in how users perceive your app—and how easily they can find their way back.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top