Handling Not Found Error in React Router
When creating an application, you need to pay attention to the appearance of various errors during its further use. In this lesson, we will learn how to work with the error 'Not Found'. Such an error can pop up, for example, if the user clicks on a link leading to a non-existent page.
First, let's open our application that we made in previous lessons and replace the layout of the Root component. Now, when we launch the application, we will see a list of two products:
function Root() {
return (
<nav>
<a href={`/products/1`}>Product1</a>
<a href={`/products/2`}>Product2</a>
</nav>
);
}
export default Root;
Let's add some styles to index.css:
body {
font-size: 18px;
line-height: 1.5;
}
nav {
display: flex;
flex-direction: column;
}
a {
text-decoration: none;
color: blue;
}
Now click on the links. Since we don't have any page layouts for our products, the links will only take us to a screen with a '404 Not Found' error and a reproach that we could have come up with something more beautiful and interesting ourselves than what React Router showed us by default.
Let's make our own page that will be displayed in case of a 404 error. To do this, in the src folder, create a file error-page-404.jsx.
Inside the React component ErrorPage404 we will use the hook useRouteError to catch the error, which we will print to the console:
import { useRouteError } from 'react-router-dom';
function ErrorPage404() {
const error = useRouteError();
console.error(error);
}
export default ErrorPage404;
Next, in the ErrorPage404 component markup, we will display a couple of headers reporting the error and output such properties of the error object as statusText and data (you can also see the error object and its properties if you open the console and start clicking on our links in the application).
return (
<div>
<h1>Hi! It is an Error Page</h1>
<h2>404 Not Found Error</h2>
<p>
<i>{error.statusText}</i>
</p>
<p>
<i>{error.data}</i>
</p>
</div>
);
Be sure to open the main.jsx file and add another import line with ErrorPage404:
import ErrorPage404 from './error-page-404';
And also add another property errorElement to the Router object - this element is displayed when an error occurs on this route. The value of the error element will be our ErrorPage404 component:
const router = createBrowserRouter([
{
path: '/',
element: <Root />,
errorElement: <ErrorPage404 />,
},
]);
Take the app you created in the previous lesson's assignment. Add a list to the home page consisting of a pair of links as shown in the lesson. Let the href values of the links be /students/1 and /students/2, and the text of the links be 'Student1' and 'Student2', respectively. Make sure that when you click the links, you get the error screen that React Router displays by default.
Now create your own separate page with error 404, you can display whatever you want on it. Connect it as shown in the lesson. Now make sure that when you click on the links you get to it.