404 Page with React Router V6.4
Tags: react, webdev, javascript, beginners
Published: 2023-05-16 11:14:50

A 404 page can be incredibly useful in improving user experience. It is displayed when a user tries to access a page that does not exist on a website. In this article, we will explore two ways to implement a 404 page using React Router V6 in our React application.

> Check out this [post on my blog](https://salehmubashar.com/blog/404-page-with-react-router-v64) too!

---

## Method 1
Suppose we have this basic route architecture:

```javascript
<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/blog" element={<Blog/>} />
  <Route path="/contact" element={<Contact/>} />
</Routes>
```

If a user enters a path that matches one of the options mentioned above, the respective component will be displayed. To add the 404 page, we can create a new route that displays the 404 page component for all paths. This can be achieved by using an asterisk (*) in the path.

As a result all paths will show the 404 component except the custom routes we have defined.

```javascript
<Routes>
  <Route path='*' element={<ErrorPage/>} />
  <Route path="/" element={<Home />} />
  <Route path="/blog" element={<Blog/>} />
  <Route path="/contact" element={<Contact/>} />
</Routes>
```

## Method 2

React Router V6.4 introduces a new hook for error handling, `useRouteError`.
> Note: This feature only works if using a [data router](https://reactrouter.com/en/main/routers/picking-a-router).

Once you have a data router installed and running, you can utilize `useRouteError` to catch any errors that occur during page loading or rendering, including the error that occurs when a page is not found. This makes debugging and error handling much simpler.

Firstly, let's create an error page:

```javascript
import { useRouteError } from "react-router-dom";

export default function ErrorPage() {
  const error = useRouteError();
  return (
    <div>
      <p style={{color: "red", fontSize:"30px"}}>
        {error.status == "404" ? "404 Page Not Found" : ""}
      </p>
    </div>
  );
}
```

In order to display an appropriate message when a page is not found using the useRouteError hook, you can simply receive the error from the hook and check its status. If the status is 404, you can return the appropriate message. Similarly, any other errors can be validated using this method.

Now we can implement this in our app. Keep in mind that we are using the new data APIs introduced in React Router V6.4. We will use the `createBrowserRouter` and `RouterProvider` to create the routes. 

```javascript
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import Home from "./Pages/Home";
import Blog from "./Pages/Blog";
import About from "./Pages/About";
import ErrorPage from "./Extras/ErrorPage";

const router = createBrowserRouter([
  {
    path: "/",
    element: <Home />,
  },
  {
    path: "/blog",
    element: <Blog />,
  },
  {
    path: "/about",
    element: <About />,
  },
]);

function App() {
  return <RouterProvider router={router} />;
}
export default App;
```

The architecture describe above works exactly like the usual Routes and Route approach. We can now add the error page using `errorElement` in the root route.

```javascript
const router = createBrowserRouter([
  {
    path: "/",
    element: <Home />,
    errorElement: <ErrorPage />
  },
  {
    path: "/blog",
    element: <Blog />,
  },
  {
    path: "/about",
    element: <About />,
  },
]);
```
The final output will look like this:

![Routing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b5sm4as3qsvuva5s4w1j.gif)

---

Thanks for reading!

Check out my [blog](https://salehmubashar.com/blog) too!