cornelc
cornelc

Reputation: 21

404 route issues with React Router and Suspense

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>

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

Upvotes: 1

Views: 1430

Answers (2)

snouck
snouck

Reputation: 135

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!

Upvotes: 2

A.San
A.San

Reputation: 11

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>

Upvotes: 1

Related Questions