How to Create a 404 Page in React Using React Router

Build a custom 404 page with a simple React route to give your visitors a helpful experience when they need it most.


Sooner or later, a user will visit a URL that doesn’t exist on your website. What the user does after that is up to you.


You could hit the back button and leave your website. Instead, you can provide a useful 404 page to help them keep navigating to your site.

For React websites, you can use the React router to create a useful 404 not found page.


Creating a 404 page

The 404 error occurs when you try to visit a page on a website that the server cannot find. As a developer, you need to deal with 404 errors by creating a page that the server uses as a fallback when it can’t find the requested page.

In React you do this by creating a not found component that is rendered on non-existent routes.

This article assumes that you already have a working React application with routing set up. If not, create a React application and then install React Router.

Create a new file called NotFound.js and add the following code to create the 404 page.

import { Link } from "react-router-dom";
export default function NotFound() {
return (
<div>
<h1>Oops! You seem to be lost.</h1>
<p>Here are some helpful links:</p>
<Link to='/'>Home</Link>
<Link to='/blog'>Blog</Link>
<Link to='/contact'>Contact</Link>
</div>
)
}

This 404 page outputs a message and links to redirect a user to general pages on the site.

Redirect to 404 page

You can create a normal route with React router like this:

import { Route, Routes } from "react-router-dom";
function App() {
return (
<Routes>
<Route path="/" element={ <Home/> }/>
</Routes>
)
}

You provide the URL path and the element you want to render on that route.

The 404 page is displayed for paths that do not exist on the site. So instead of specifying the path, use an asterisk (*).

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

Use * renders the NotFound component for all URLs not specified in routes.

Redirect in React

With a router, you can easily create a 404 page for any URL that doesn’t exist in your React web app.

Browsers have a standard 404 page, but creating a custom page lets your users know what went wrong and how to fix it. You can also create a 404 page that fits your brand.

Leave a Reply

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