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
NoMatchPagecomponent will never be shown. - Written inside the Suspense, as the last child, will render the
NoMatchPagecomponent on any route, placed after the component that should be rendered on that path. - Written just above the Suspense, will render the
NoMatchPagecomponent 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.
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: