In this post we'll see how to set up an error page (Page not found page) in React Router.
Why do we need error page
If user tries to access URL that doesn't match any configured routes in your application an empty page is displayed to the user. To avoid that you can set a custom error page that will be displayed in case of such routing error. That provides for a better user experience rather than just showing an empty page.
How to set up error page
React Router provides different ways to implement an error or page not found page.
- To use a wild card route (with path as "/*") as a catch all route.
- Using useRouteError() hook with errorElement prop.
1. Setting up 404 page using wild card route
If you are using a catch all route to set up an error page then the steps are as given below.
- Create an error component that would be displayed in case there is no match for the URL.
- In your route configuration provide route definition for error page (path as “/*”) as the last one, otherwise it will match all the routes and you will always end up in the error component.
Error Component
Component that will be rendered if there is any error.
src\components\routes\ErrorPage.js
const ErrorPage = () => { return ( <div> <h2 style={{color: "red"}}>Page Not Found (404) error!!</h2> <p>Page you are trying to access doesn't exist.</p> </div> ); } export default ErrorPage;
Route Configuration
import { BrowserRouter, Route, Routes } from 'react-router'; import About from './components/routes/about'; import Home from './components/routes/home'; import NavigationNavLink from './components/routes/NavigationNavLink'; import ErrorPage from './components/routes/ErrorPage'; function App() { return ( <> <BrowserRouter > <Routes> <Route path="/" element={<NavigationNavLink />}> <Route index element={<Home />} /> <Route path="about" element={<About />} /> <Route path="*" element={<ErrorPage />} /> </Route> </Routes> </BrowserRouter> </> ); } export default App;
To get code for other components please refer this post- Using NavLink in React Router
With that if you try to access any path that doesn't exist.
2. Using useRouteError() hook with errorElement prop
Another way to set up error page is to use useRouterError() hook but that works with data and framework modes not with declarative mode.
Error Component
Component that will be rendered if there is any error.
src\components\routes\ErrorPage.js
import { isRouteErrorResponse, useRouteError } from "react-router"; const ErrorPage = () => { const error = useRouteError(); console.log(error); if (isRouteErrorResponse(error)) { return ( <> <h1> {error.status} {error.statusText} </h1> <p>{error.data}</p> </> ); } else if (error instanceof Error) { return ( <div> <h1>Error</h1> <p>{error.message}</p> <p>The stack trace is:</p> <pre>{error.stack}</pre> </div> ); } else { return <h1>Unknown Error</h1>; } } export default ErrorPage;
As you can see useRouteError() hook is used to get access to the error thrown during an ActionFunction, LoaderFunction, or component render.
Using isRouteErrorResponse you can check if the given error is an ErrorResponse generated from a 4xx/5xx Response thrown from an action/loader.
Since this will work with data or framework mode so route configuration is done using createBrowserRouter function in a separate file.
src\components\routes\Route.jsimport { createBrowserRouter } from "react-router"; import About from "./About"; import Home from "./Home"; import NavigationNavLink from "./NavigationNavLink"; import ErrorPage from "./ErrorPage"; export const route = createBrowserRouter([ {path: "/", element: <NavigationNavLink />, errorElement: <ErrorPage />, children: [ {index: true, element: <Home /> }, {path: "/about", element: <About />} ] } ])
You can see the Error page is set using the errorElement prop in the parent route. Even if an error occurs in the Child component, it will bubble up to the Root route where <ErrorPage /> component defined in the errorElement prop will catch that error.
In App.js add the Route Provider.
import { route } from './components/routes/Route'; import { RouterProvider } from 'react-router'; function App() { return ( <RouterProvider router={route}></RouterProvider> ); } export default App;
To get code for other components please refer this post- Using NavLink in React Router
With that if you try to access any path that doesn't exist.
That's all for this topic Setting 404 Error Page With React Router. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-
No comments:
Post a Comment