Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React lazy loaded route makes redirecting non-matching routes to /404 not work

I've been trying to make a 404 not found page and redirect all non-matched routes there, currently configured with whole context as:

<Switch>
  <Route path="/faq" component={FAQ}></Route>

  <Route path="/404">
    <NotFound />
  </Route>

  <Suspense fallback={<div>Loading ...</div>}>
    <Route path="/admin" component={AdminModule}></Route>
  </Suspense>

  <Redirect exact={true} from="*" to="/404" />
</Switch>
  • If I move the redirect component above the suspense with the lazy loaded component, I'll no longer be able to activate routes for admin module.
  • If I move everything after the Suspense including the /404, It no longer loads the NotFound component for the /404 route even when navigating to it manually.

Tried various other solutions that I've found in the docs but none of them seem to work, is this by design or a bug? if it's by design, what is the design? It seems like a use case that every single app out there would need.

like image 555
SebastianG Avatar asked Jun 04 '20 11:06

SebastianG


Video Answer


1 Answers

You should not usw Suspense inside Switch. Your Switch must be wrapped by Suspense component.

<Suspense fallback={<div>Loading ...</div>}>
    <Switch>
     <Route path="/faq" component={FAQ}></Route>

     <Route path="/404">
         <NotFound />
     </Route>

     <Route path="/admin" component={AdminModule}></Route>

     <Redirect exact={true} from="*" to="/404" />
  </Switch>
</Suspense>
like image 92
luggi Avatar answered Oct 09 '22 10:10

luggi