skip to Main Content

In my react app I’m trying to render custom error component for unmatched routes but default error page is shown.

This is how my browserRouter looks.

const router = createBrowserRouter([
  {
    path: "/feed",
    element: <App />,
    errorElement: <ErrorPage />,
    children: [
      {
        index: true,
        element: <Feed />,
      },
      {
        path: "/feed/login",
        element: <Login />,
      },
    ],
  },
]); 

P.S. If I have root path as just '/' it works fine. But if let’s say I want my root path to be '/feed' then the error component is not getting rendered.

import React from 'react';
import { Link, useRouteError } from 'react-router-dom';

const ErrorPage = () => {
  const error = useRouteError()
  
  return (
    <div className='w-full h-screen flex flex-col items-center mt-28'>
      <h1 className='text-8xl text-neutral-grayish-blue'>Error <span className='text-8xl text-primary-soft-red'>{error.status}</span></h1>
      <p className='text-4xl text-neutral-grayish-blue my-10'>{error.statusText}</p>
      <Link to={'/feed'} className='p-2 bg-neutral-dark-blue text-neutral-white rounded-md'>Back Home</Link>
    </div>
  );
};

export default ErrorPage;

2

Answers


  1. errorElement s not for unmatched routes, for your problem you can add another root object with path * (means anywhere but your created paths) and there add your page

    Login or Signup to reply.
  2. Your app is using the default error boundary component. Remember that errors bubble up. Move the ErrorPage error boundary component up higher in the routing tree than the route that generates the error.

    Example:

    const router = createBrowserRouter([
      {
        errorElement: <ErrorPage />, // <-- root error component
        children: [
          {
            path: "/feed",
            children: [
              {
                index: true,
                element: <Feed />
              },
              {
                path: "/feed/login",
                element: <Login />
              }
            ]
          }
        ]
      }
    ]);
    

    Demo

    Demo sandbox tries to access unknown route "/foo".

    enter image description here

    Edit react-router-6-errorelement-not-rendering-an-error-component

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search