404 Page and Wildcard Routes
Learn to handle undefined routes in React by creating a 404 page with wildcard routes.
In web applications, users may encounter missing or 404 pages for various reasons, such as:
Typing an incorrect URL.
Following a broken or outdated link.
Trying to access a resource that no longer exists.
What is a 404 page?
A 404 page provides a user-friendly way to inform visitors that the requested page cannot be found. It often includes helpful navigation options, such as links to the Home page or a search feature, guiding users back to valid content.
Wildcard routes in React Router
React Router allows us to define a wildcard route (path="*"
) to handle any undefined paths in our application. Wildcard routes are typically used to display 404 pages.
Key points:
Wildcard routes should be placed at the bottom of our
Routes
list since React Router matches routes in order.They act as a fallback for any path that doesn’t match a defined route
Creating a 404 page
A 404 page provides a friendly error message and navigation links. Let’s create a custom 404 page and use a wildcard route to display it for undefined paths.