Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router Lazy Component isn't working

So this works:

import Page from 'components/Page';
...

render() {
   return (
     <Route render={props => <Page {...props}/>}/>
   );
}

But this doesn't:

import React, { lazy } from 'react';
const Cmp = lazy(() => import('components/Page'));
...

render() {
   return (
     <Route render={props => <Cmp {...props}/>}/>
   );
}

React 16.8.6 React Router 5.0.0

I get this:

The above error occurred in one of your React components:
    in Unknown (at configured.route.js:41)
    in Route (at configured.route.js:41)
    in ConfiguredRoute (created by Context.Consumer)
    ...rest of stack trace

Can anyone see what stupid thing I am doing here?

like image 683
Adam Avatar asked May 21 '19 23:05

Adam


2 Answers

Referencing the React Docs on code splitting, the recommendation is to use Suspense with a defined fallback so you have something to render in place of the components when they haven't loaded.

// Direct paste from https://reactjs.org/docs/code-splitting.html

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';

const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));

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

Suspense should be a parent of the <Route> elements that use lazy

like image 118
John Ruddell Avatar answered Nov 10 '22 21:11

John Ruddell


I updated the version of react and this error started to show up because I forgot to also update the react-dom package version, once I did that everything worked fine.

like image 33
a.guerrero.g87 Avatar answered Nov 10 '22 20:11

a.guerrero.g87