tetar
tetar

Reputation: 872

'react-router-dom 404 for subRoute

i want to set a 404 page for my subroute there is my router

    <Router>
  <Suspense fallback={<Loader type="circle" />}>
    <Switch>
      <PublicRoute path="/" exact isAuthenticated={0}>
        <Home />
      </PublicRoute>
      <PublicRoute path="/login" exact isAuthenticated={0}>
        <Login />
      </PublicRoute>
      <PrivateRoute path="/private" isAuthenticated={1}>
        <ProtectedRoutes />
      </PrivateRoute>
      <Route>
        <NotFound />
      </Route>
    </Switch>
  </Suspense>
</Router>

for my public route i have my component working

but for my ProtectedRoute =>

 const ProtectedRoute = () => (
  <Switch>
    <Suspense fallback={<Loader type="circle" />}>
      {routes.map(({ component: Component, path, exact }) => (
        <Route path={`/private/${path}`} key={path} exact={exact}>
          <Component />
        </Route>
      ))}
    </Suspense>
  </Switch>
);



   const routes = [
  {
    path: 'test',
    component: lazy(() => import('../components/private/logged/index')),
  },
  {
    path: 'otherTest',
    component: lazy(() => import('../components/private/logged/index')),
  }
];

I try many solution and i m stuck i don't know what to do to create a 404 page when user go in wrong route while in XXXXX/private/

Upvotes: 0

Views: 60

Answers (2)

tetar
tetar

Reputation: 872

just need to remove =>

   <Suspense fallback={<Loader type="circle" />}> && </Suspense>

from the official documentation that i read, there is an example that Switch component is working inside Suspense component.

Upvotes: 0

Dmitriif
Dmitriif

Reputation: 2433

You have a new switch statement for protected routes, so you have to add one more route for 404 page inside it.

const ProtectedRoute = () => (
 <Switch>
   <Suspense fallback={<Loader type="circle" />}>
     {routes.map(({ component: Component, path, exact }) => (
       <Route path={`/private/${path}`} key={path} exact={exact}>
         <Component />
       </Route>
     ))}
   <Route path='*'>
       <NotFound />
     </Route>
   </Suspense>
 </Switch>
);

Upvotes: 1

Related Questions