Handling 404 Pages and Fallback Routes

Introduction

In any web application, it’s common for users to enter URLs that do not match existing routes. Without proper handling, this results in blank pages or broken navigation, which leads to poor user experience. React Router provides tools to handle 404 pages and fallback routes, ensuring users are guided appropriately when they visit unknown paths.

In this post, we will cover:

  • Using a catch-all route for undefined paths
  • Rendering a 404 Not Found page
  • Redirecting users to the home or login page
  • A practical example of a 404 component with navigation options

By the end, you will understand how to implement robust route handling for any React application.


Catch-All Route Using path="*"

React Router allows you to define a catch-all route using path="*". This route will match any URL that does not match existing routes, effectively serving as a fallback.

Example:

import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
import NotFound from './NotFound';

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

Explanation:

  • The path="*" route catches all unmatched URLs.
  • Placing it at the end of Routes ensures React Router first checks all defined routes before using the fallback.
  • This route typically renders a 404 component with helpful information for the user.

Rendering a 404 Not Found Page

A 404 page informs users that the requested resource does not exist. It often includes navigation options to guide users back to valid pages.

Basic 404 Component

import React from 'react';
import { Link } from 'react-router-dom';

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

Explanation:

  • Provides a clear message indicating the page is not found.
  • Includes a link back to the home page for easy navigation.
  • Can be customized with images, animations, or suggestions for similar pages.

Redirecting Unknown URLs to Home or Login Page

Instead of rendering a dedicated 404 page, some applications prefer to redirect unknown URLs to a safe location, such as the home page or login page.

Using Navigate for Redirection

import { Navigate } from 'react-router-dom';

function App() {
  const isAuthenticated = false;

  return (
<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/login" element={<Login />} />
    <Route
      path="*"
      element={isAuthenticated ? <Navigate to="/" /> : <Navigate to="/login" />}
    />
  </Routes>
</BrowserRouter>
); }

Explanation:

  • Navigate component allows programmatic redirection.
  • Unmatched routes redirect users based on authentication state.
  • Ensures users always land on a valid page, preventing dead-ends.

Example: 404 Component with Navigation Options

A 404 page can be enhanced with navigation options, search functionality, or links to key sections.

Full Example

import React from 'react';
import { Link } from 'react-router-dom';

function NotFound() {
  return (
<div style={{ textAlign: 'center', padding: '50px' }}>
  <h1>404 - Page Not Found</h1>
  <p>Oops! The page you requested could not be found.</p>
  <div style={{ marginTop: '20px' }}>
    <Link to="/" style={{ margin: '0 10px' }}>Home</Link>
    <Link to="/about" style={{ margin: '0 10px' }}>About</Link>
    <Link to="/contact" style={{ margin: '0 10px' }}>Contact</Link>
  </div>
  <p style={{ marginTop: '20px' }}>
    Or try searching for what you are looking for.
  </p>
  <input
    type="text"
    placeholder="Search..."
    style={{ padding: '10px', width: '300px', marginTop: '10px' }}
  />
</div>
); } export default NotFound;

Features:

  • Clear 404 message.
  • Links to important pages for easy navigation.
  • Optional search input to help users find content.
  • Can be extended with site map or suggestions.

Handling 404 Pages with Nested Routes

If your application has nested routes, you can define a catch-all for child routes as well:

<Routes>
  <Route path="/dashboard" element={<Dashboard />}>
&lt;Route path="profile" element={&lt;Profile /&gt;} /&gt;
&lt;Route path="settings" element={&lt;Settings /&gt;} /&gt;
&lt;Route path="*" element={&lt;NotFound /&gt;} /&gt; {/* Catch-all for dashboard */}
</Route> <Route path="*" element={<NotFound />} /> {/* Global catch-all */} </Routes>

Explanation:

  • Unmatched child routes under /dashboard show a dashboard-specific 404.
  • Global unmatched routes show a site-wide 404.
  • Improves user guidance in complex applications.

Best Practices for 404 Handling

  1. Always provide a fallback route using path="*".
  2. Include navigation options in the 404 page to help users recover.
  3. Use redirection carefully; avoid confusing users by sending them to unrelated pages.
  4. Customize styling and content to maintain branding consistency.
  5. Support nested routes to handle 404 errors in sub-sections of your app.

Benefits of Handling 404 Pages Properly

  • Enhanced user experience: Users aren’t left with blank pages.
  • Improved navigation: Links guide users back to valid content.
  • Professional appearance: Custom 404 pages make your app look polished.
  • Error tracking: Helps identify broken links or missing content in the app.

Comments

Leave a Reply

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