I'm trying to show an error message on the same page if there's an error when loading a resource. However, when using loader and errorElement, the user is taken to another page. How can I do it so I show the error on my component and not redirect the user to a new component/view?
Example of what I'm doing:
const router = createBrowserRouter([
{
path: "/",
element: <Root />,
errorElement: <ErrorPage />,
loader: rootLoader,
children: [
{
path: "contacts/:contactId",
element: <Contact />,
},
],
},
]);
I've tried several things.
When I do the things as in the example, the user is redirected to the errorComponent. That would be fine if the application had a fatal error but not if the application has a 422 error for example. In that case, I would like an error alert/snack to appear.
I've also tried to use the same component for the error. This didn't load the error message that I was looking for.
You can specify an errorElement for specific routes if you like. The errorElement is a sort of "error boundary" for route loading, the closest one at or above a route that is being loaded is rendered when there's an error.
Example:
const router = createBrowserRouter([
{
path: "/",
element: <Root />,
errorElement: <ErrorPage />,
loader: rootLoader,
children: [
{
path: "contacts/:contactId",
element: <Contact />,
errorElement: <ContactErrorPage />, // <-- specific to route
loader: contactLoader,
},
],
},
]);
You can use the same component for both element and errorElement and useRouteError in that component
Example : https://replit.com/@ptrkcsk/React-Router-useRouteError
import { createBrowserRouter, useRouteError } from "react-router-dom";
const router = createBrowserRouter([
{
path: "/",
element: <Root />,
errorElement: <Root />,
loader: () => {
throw new Error("Error");
},
},
]);
function Root() {
const routeError = useRouteError();
return routeError ? routeError.message : null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With