Dream High
Dream High

Reputation: 173

How to use React.lazy for a component of a module?

I am using the npm package called '@toast-ui/react-editor'. It includes a 'Viewer' react component. I could just use:

const Viewer = require("@toast-ui/react-editor").Viewer

But it increases the bundle size a lot. So I wanted to load it lazily whenever it is needed by using React.lazy. I am going to use it inside component:

<Viewer {...props} />

But I don't have any clue how to do it.

I tried this way, but didn't work.

const Lazy = React.lazy(() => import(require("@toast-ui/react-editor"))).Viewer;

I really want to know how to do it.

Upvotes: 10

Views: 8528

Answers (1)

dance2die
dance2die

Reputation: 36985

As Viewer is not a default component, it's not as simple as removing require, (which is not even needed, though).

You need to import it dynamically and then return the module as a default one (as that's what lazy expects and works with only).

const Viewer = lazy(() =>
  import("@toast-ui/react-editor").then(module => {
    return { default: module.Viewer };
  })
);

Upvotes: 21

Related Questions