Sooner or later, a user will visit a URL that doesn’t exist on your website. What the user does after this is up to you. They might press the back button and leave your site. Instead, you can provide a useful 404 page to help them continue to navigate to your website.

For React websites, you can use React router to create a useful 404 not found page that renders when a user visits a route that doesn’t exist.

​​​​​

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, handling 404 errors means creating a page that the server uses as a replacement when it can’t find the requested page.

This article assumes you already have a working React application with routing set up. If you don’t, create a React application and 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 React 404 page renders a message and links to redirect a user to common pages on the website.

Routing to the 404 Page

You specify routes using React router by specifying the URL path and the component you want to render for that route.

For example, below is a route that renders the Home component.

        import { Route, Routes } from "react-router-dom";

function App() {
    return (
        <Routes>
            <Route path="/" element={ <Home/> }/>
        </Routes>
    )
}

The 404 error page displays paths that don’t exist on the website. So, instead of specifying the path, use an asterisk (*) to match anything.

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

The NotFound component will render for all the URLs not specified in routes.

Routing in React

​​​​​​Browsers have a default 404 page but creating a custom one allows you to tell your users what went wrong and how they can fix it. You can easily create a React 404 page for all URLs that don’t exist in your web app using a react-router-dom. You can also style it according to your brand.