Handling 404 Pages with React Router

 ๐Ÿšง Handling 404 Pages with React Router

When building a React app with React Router, it's important to show a custom 404 page when users navigate to a URL that doesn’t match any of your routes.


How to Set Up a 404 Page

1. Create a 404 Component

First, create a simple component to display the "Page Not Found" message:


jsx

Copy

Edit

// NotFound.js

import React from 'react';


const NotFound = () => {

  return (

    <div style={{ padding: '2rem', textAlign: 'center' }}>

      <h1>404 - Page Not Found</h1>

      <p>Sorry, the page you’re looking for does not exist.</p>

    </div>

  );

};


export default NotFound;

2. Add a Route for 404

Use React Router’s <Route> with a wildcard or a catch-all path to display the NotFound component for unmatched routes.


Example Using React Router v6

jsx

Copy

Edit

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

import Home from './Home';

import About from './About';

import NotFound from './NotFound';


function App() {

  return (

    <Router>

      <Routes>

        <Route path="/" element={<Home />} />

        <Route path="/about" element={<About />} />

        

        {/* Catch-all route for 404 */}

        <Route path="*" element={<NotFound />} />

      </Routes>

    </Router>

  );

}


export default App;

The path="*" route matches any URL not matched by previous routes.


It should be placed last inside <Routes> because routes are matched in order.


3. Testing the 404 Page

Try navigating to a non-existent URL like /random-page. You should see your custom 404 page.


Notes:

In React Router v5, use <Switch> and add a <Route component={NotFound} /> without a path prop as the last route.


For better UX, you can add links or buttons on the 404 page to redirect users back to the home page.


✅ Summary

Create a dedicated 404 component.


Add a wildcard route (path="*") at the end of your routes.


This route renders the 404 page when no other route matches.

Learn React JS Course in Hyderabad

Read More

How to Use URL Parameters in React Router

Programmatic Navigation in React

Nested Routes in React Explained

Setting Up React Router (v6)

Visit Our Quality Thought Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Installing Tosca: Step-by-Step Guide for Beginners

Why Data Science Course?