React.js / React Routing and Navigation

Handling 404 Pages and Redirects

This tutorial will guide you through handling 404 pages and implementing redirects in your React application. You'll learn how to provide appropriate feedback when a page isn't fo…

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Covers implementing client-side routing and navigation with React Router.

1. Introduction

Goal of the tutorial: This tutorial aims to teach you how to manage 404 pages and implement redirects in a React application.

Learning outcomes: By the end of this tutorial, you'll be able to provide an appropriate user feedback when a page isn't found and direct users to the correct content using redirects.

Prerequisites: Basic understanding of React and JavaScript is required.

2. Step-by-Step Guide

404 is the HTTP status code for not found. This means the server could not find the requested URL. In a React application, we can handle 404s by using routing. When none of the routes match, we can return a 404 page.

Redirects are a way to send both users and search engines to a different URL from the one they originally requested. We can implement redirects in our React application using the Redirect component from react-router-dom.

Installing react-router-dom

Before we start, ensure that you have react-router-dom installed. If not, install it using:

npm install react-router-dom

Basic Route Setup

First, let's set up some basic routes. For this, we'll need the BrowserRouter and Route components from react-router-dom.

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

function App() {
  return (
    <Router>
      <Route path="/" exact component={HomePage} />
      <Route path="/about" component={AboutPage} />
      <Route path="/contact" component={ContactPage} />
    </Router>
  );
}

export default App;

3. Code Examples

Handling 404

To handle 404s, we can use the Switch component from react-router-dom. The Switch component will only render the first Route or Redirect that matches the location. So, if none of the routes match, we can return a 404 page.

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

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/" exact component={HomePage} />
        <Route path="/about" component={AboutPage} />
        <Route path="/contact" component={ContactPage} />
        <Route component={NotFoundPage} />
      </Switch>
    </Router>
  );
}

export default App;

In the above code, if the URL doesn't match any of the first three routes, the NotFoundPage component will be rendered.

Implementing Redirects

We can implement redirects using the Redirect component from react-router-dom. For example, if we want to redirect from /old-path to /new-path, we can do:

import React from 'react';
import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/" exact component={HomePage} />
        <Route path="/about" component={AboutPage} />
        <Route path="/contact" component={ContactPage} />
        <Redirect from="/old-path" to="/new-path" />
        <Route component={NotFoundPage} />
      </Switch>
    </Router>
  );
}

export default App;

In the above code, if the URL is /old-path, it will redirect to /new-path.

4. Summary

In this tutorial, we have learned how to handle 404 pages and implement redirects in a React application. We used the react-router-dom library to achieve this.

5. Practice Exercises

  1. Create a simple React application with routes for Home, About, and Contact pages. Implement a 404 page that displays when the URL doesn't match any of these routes.

  2. Add a redirect from /old-about to /about. Test this by visiting /old-about and verifying that you are redirected to /about.

Solutions

  1. This is similar to the code example provided in the tutorial. You just need to create the HomePage, AboutPage, ContactPage, and NotFoundPage components and use them in the routes.

  2. This is also similar to the code example provided in the tutorial. You just need to add <Redirect from="/old-about" to="/about" /> to your routes.

Remember, practice makes perfect. Continue to experiment with different routes and redirects. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Favicon Generator

Create favicons from images.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

Image Converter

Convert between different image formats.

Use tool

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help