Nicholas Domenichini
Nicholas Domenichini

Reputation: 870

React Lazy loading import failing

My component looks something like this, of course with a few unimportant details omitted:

import React from 'react';
import { createMuiTheme, MuiThemeProvider, withStyles } from "@material-ui/core/styles";
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import Tooltip from '@material-ui/core/Tooltip';
import { connect } from 'react-redux';
const DialogBox = React.lazy(() => import('./DialogBox'));

const mapStateToProps = (state, ownProps) => {
  return {
    answer: state.answers[state.stepper][ownProps.obj.ID]
  }
}

const mapDispatchToProps = { }


class FlexiblePopupSelect extends React.Component {
  render() {
    return (
      <React.Fragment>
        <DialogBox />
      </React.Fragment>
    )
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withStyles(styles)(FlexiblePopupSelect));

When I replace the const DialogBox = React.lazy(() => import('./DialogBox')); line with a normal import DialogBox from './DialogBox', everything works fine. I followed this guide from React's site, but with no success. Where did I go wrong here?

EDIT:

There was no real error message, it just gives me a bunch of error messages that say "The above error occurred in one of your React components" but it never gives me any error message above.

I am using React 16.8.6 with Create-React-App handling the Webpack side of things.

EDIT 2:

After a bit of fiddling, I found out that the fix was using the <Suspense> component from react like so:

<React.Fragment>
  <Suspense>
    <DialogBox />
  </Suspense>
</React.Fragment>

Upvotes: 4

Views: 8665

Answers (1)

dance2die
dance2die

Reputation: 36985

You need to wrap your lazily component with React.Suspense by providing the fallback component to show. (such as a message or a loading gif etc).

You can safely replace React.Fragment with React.Suspense.

class FlexiblePopupSelect extends React.Component {
  render() {
    return (
      <React.Suspense fallback={<div>Loading dialog box...</div>}>
        <DialogBox />
      </React.Suspense>
    )
  }
}

For more info, check out Code-Splitting > Suspense documentation.

Upvotes: 2

Related Questions