Now that we know how to handle the basic routes; let’s look at handling 404s with the React Router. These are cases when a user goes to a URL that we are not explicitly handling. We want to show a helpful sign to our users when this happens.

Create a Component

Let’s start by creating a component that will handle this for us.

Change indicator Create a new component at src/containers/NotFound.tsx and add the following.

import "./NotFound.css";

export default function NotFound() {
  return (
    <div className="NotFound text-center">
      <h3>Sorry, page not found!</h3>
    </div>
  );
}

All this component does is print out a simple message for us.

Change indicator Let’s add a couple of styles for it in src/containers/NotFound.css.

.NotFound {
  padding-top: 100px;
}

Add a Catch All Route

Now we just need to add this component to our routes to handle our 404s.

Change indicator Find the <Routes> block in src/Routes.tsx and add it as the last line in that section.

{/* Finally, catch all unmatched routes */}
<Route path="*" element={<NotFound />} />;

This needs to always be the last route in the <Routes> block. You can think of it as the route that handles requests in case all the other routes before it have failed.

Change indicator And include the NotFound component in the header by adding the following:

import NotFound from "./containers/NotFound.tsx";

And that’s it! Now if you were to switch over to your browser and try clicking on the Login or Signup buttons in the Nav you should see the 404 message that we have.

Router 404 page screenshot

Next up, we are going to allow our users to login and sign up for our app!