0
votes

I'm trying to use lazy loading, with Suspense, from React 16.12.0. I'm also using React Router 5.1.2.

It's the first time I'm using Suspense and I haven't managed to find a proper way to load a 404/NoMatch without causing other issues.

My code looks like this:

import Component1 from 'path'
import Component2 from 'path'
import NoMatchPage from 'path'
const Component3 = lazy(()=>import('path'));
const Component4 = lazy(()=>import('path'));

<Router>
   <Switch>
        <Route exact path="/route-1" component={Component1}/>
        <Route exact path="/route-2" component={Component2}/>
        <Suspense fallback={<Loader/>}>
            <Route exact path="/route-3" component={Component3}/>
            <Route exact path="/route-4" component={Component4}/>
        </Suspense>
        <Route component={NoMatchPage}/>
   <Switch>
</Router>

  • Written like this, the NoMatchPage component will never be shown.
  • Written inside the Suspense, as the last child, will render the NoMatchPage component on any route, placed after the component that should be rendered on that path.
  • Written just above the Suspense, will render the NoMatchPage component on any route, placed before the component that should be rendered on that path.

I've checked the official documentation and a lot practical examples, but I've found nothing that could help me with this issue.

2

2 Answers

0
votes

Maybe you have figured it out, but try to nest the suspense inside the route like this and do it for each route you want to have suspense fallback on:

<Route exact path="/route-3"/>
 <Suspense fallback={<Loader />}>
  <Component3/>
 </Suspense>
</Route>

0
votes

from the official documentation that i read, there is an example that Switch component is working inside Suspense component. So maybe for your issue, you can try to move Switch component into Suspense component (order of component Suspense is higher than component Switch). Below is an example.

  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/about" component={About}/>
      </Switch>
    </Suspense>
  </Router>

Good luck!