Search code examples
reactjsreact-router-domvite

ErrorHandling React Router v6 is not working?


I tried to handle any errors occured that breaks my application using React Router Dom - ErrorHandling. But seems like it's not working. What am I missing in this code?

My App Code

import ErrorHandling from "./ErrorHandling"

// prettier-ignore
export default memo(function AppLayout() {
  const location = useLocation()
  return (
    <>
      <Toaster />
      <AnimatePresence mode="wait" initial={false}>
        <Routes location={location} key={location.pathname}>
          <Route path={`/`} element={<AppLayer><Navigate to={`/v3/dashboard`} /></AppLayer>}/>
          <Route path={`/v3/`} element={<AppLayer><Navigate to={`/v3/dashboard`} /></AppLayer>}/>
          <Route path={`/v3`} element={<AppLayer></AppLayer>} errorElement={<ErrorHandling/>}>
            <Route path={`login`} element={<Login />} />

My App Layer

export const dashboardContext = createContext()

// prettier-ignore
export default function AppLayer({children}) {

  // dashboard context
  const [data, setData] = useState(false)

  // check if user is login
  if (!AuthHelpers.is_user_login()) window.location.href = "/v3/login"

  return (
    <dashboardContext.Provider value={{data, setData}}>
      <AppData>
        <Outlet />
      </AppData>
    </dashboardContext.Provider>
  )
}

My Error Handling Component

import React from "react"
import {useRouteError} from "react-router-dom"

export default function ErrorHandling() {
  const error = useRouteError()
  console.log(error)
  return (
    <div className="text-center w-screen h-screen flex flex-col items-center justify-center text-neutral-70">
      <h1 className="text-48">Error!</h1>
      <p className="text-24">Something's Wrong.</p>
    </div>
  )
}

I expect the errors to be redirected to ErrorElement instead of blank white page.


Solution

  • As they say in the documentation,

    This feature only works if using a data router, see Picking a Router

    but you are using it in a BrowserRouter, so it won't work.