Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router with React 16.6 Suspense "Invalid prop `component` of type `object` supplied to `Route`, expected `function`."

I'm using the latest version (16.6) of React with react-router (4.3.1) and trying to use code splitting using React.Suspense.

Although my routing is working and the code did split into several bundles loaded dynamically, I'm getting a warning about not returning a function, but an object to Route. My code:

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

import Loading from 'common/Loading';

const Prime = lazy(() => import('modules/Prime'));
const Demo = lazy(() => import('modules/Demo'));

const App = () => (
  <Suspense fallback={<Loading>Loading...</Loading>}>
    <Switch>
      <Route path="/" component={Prime} exact />
      <Route path="/demo" component={Demo} />
    </Switch>
  </Suspense>
);

export default withRouter(App);

The console warning is as follows: Warning: Failed prop type: Invalid prop `component` of type `object` supplied to `Route`, expected `function`.

A normal import would return a function, but the dynamic import with lazy() is returning an object.

Any fixes for this?

like image 821
ronnyrr Avatar asked Oct 26 '18 11:10

ronnyrr


2 Answers

Try using render prop instead of component

<Route path="/" render={()=> <Prime />} exact />
<Route path="/demo" render={()=> <Demo />} />
like image 174
Byrd Avatar answered Nov 10 '22 19:11

Byrd


This will be fixed in react-router-dom version 4.4+ as this issue suggests

You can wait for the final release or if you don't want to change your code today, you can install the beta version now by yarn add react-router-dom@next

like image 30
zenoh Avatar answered Nov 10 '22 19:11

zenoh