reactjses6-module-loaderreact-suspense

Can you deconstruct lazily loaded React components?


Using es6 imports, you can do this:

import { MyComponent } from "../path/to/components.js";

export default function () {
  return <MyComponent/>;
}

Can I do it with React.lazy too?

const { MyComponent } = lazy(() => import("../path/to/components.js"));

I get the following error, but I'm not sure if it's related to this or some other bug I have:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined


Solution

  • You can if you use react-lazily.

    import { lazily } from 'react-lazily';
    const { MyComponent } = lazily(() => import("../path/to/components.js"));
    

    It also allows importing more than one component:

    const { MyComponent, MyOtherComponent, SomeOtherComponent } = lazily(
      () => import("../path/to/components.js")
    );
    

    See this answer for more options.