When using react-router 6.18 the top level errorElement
is not rendered on error. I define my routes like this:
Routes.tsx
const routes = [
{
element:(
<>
<h1>WRAPPER</h1>
<Outlet />
</>
),
errorElement: <h1>ERROR PAGE</h1>,
children: [
{
path: '/',
element: (
<>
<h1>MAIN PAGE</h1>
<Outlet />
</>
),
children: [
{
index: true,
//loader: () => {throwAuthenticationError()},
element: <><h2>CHILD PAGE</h2>{throwAuthenticationError()}</>
}
]
}
]
}
]
export const router = createBrowserRouter(routes);
index.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { RouterProvider } from 'react-router-dom';
import { router } from 'Routes';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>MY APP</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
and use the following function to throw the error:
export default function throwAuthenticationError(errorMessage: string, error?: unknown): never {
console.error(errorMessage);
if(error) {
console.error("Caught Error:");
console.error(error);
}
throw new Response("You were logged out", { status: 401 });
}
When I throw the error in the loader the error element is rendered as expected. However when I throw it in the element Uncaught runtime error overlay is rendered and when I close it there is just a blank screen underneath. Why is that? And how can I fix it? I have also tried to include the errorElement in each route but it does not seem to have an effect.
Here is the whole error message:
Uncaught runtime errors:
ERROR
[object Response]
handleError@http://localhost:3000/static/js/bundle.js:667010:67
@http://localhost:3000/static/js/bundle.js:667029:18
Console output:
[Error] [object Response]
__webpack_require__ (bundle.js:765864)
(anonymous function) (bundle.js:767119)
Global Code (bundle.js:767121)