We are trying to use react-error-boundary with react-router (v6) but seems like we need to wrap every route element with an error boundary as shown below
import { ErrorBoundary } from "react-error-boundary";
export const AppRoutes = createBrowserRouter([
{
path: "/",
element: <ErrorBoundary FallbackComponent={GlobalError}><Login /></ErrorBoundary>
},
{
path: "login",
element: <ErrorBoundary FallbackComponent={GlobalError}><Login /></ErrorBoundary>,
},
{
path: "trans",
element: <ErrorBoundary FallbackComponent={GlobalError}><Trans /></ErrorBoundary>
),
{
path: "*",
element: <ErrorBoundary FallbackComponent={GlobalError}><RouteNotFound /></ErrorBoundary>
}]);
Do we have a simpler way to do this like below? Any configuration flag in react-router to bubble up the error
import { ErrorBoundary } from "react-error-boundary";
<ErrorBoundary FallbackComponent={GlobalError}>
<Header />
<RouterProvider router={AppRoutes} />
<Footer />
</ErrorBoundary>
Below is the screenshot of the error we get when we wrap the RouterProvider inside the Error Boundary
Below is a sample code for the Trans component to throw an error.
export function Trans() {
const [error, setError] = useState(null);
if (error) {
throw error;
}
useEffect(() => {
setTimeout(() => setError("This is error"), 2000);
}, []);
return <p>This is Trans</p>;
}