🦥 React.lazy without a default export
React v16.6.0 introduced React.lazy that allows to code split without any external libraries.
https://reactjs.org/blog/2018/10/23/react-v-16-6.html
The React.lazy function lets you render a dynamic import as a regular component.
Before:
import OtherComponent from "./OtherComponent"; function MyComponent() { return ( <div> <OtherComponent /> </div> ); }After:
const OtherComponent = React.lazy(() => import("./OtherComponent")); function MyComponent() { return ( <div> <OtherComponent /> </div> ); }
Althought bellow there is a message
React.lazytakes a function that must call a dynamicimport(). This must return aPromisewhich resolves to a module with adefaultexport containing a React component.
Which means that your OtherComponent should be exported this way
export default function OtherComponent() {
return <div>OtherComponent</div>;
}
But what if you have it exported not as default?
export function OtherComponent() {
return <div>OtherComponent</div>;
}
In this case you have to change a bit the import() code when importing this component
const OtherComponent = React.lazy(() =>
import("./OtherComponent").then((module) => ({
default: module.OtherComponent,
})),
);
What are we doing here, is just chaining the Promise returned by import() and adding that default export.
Please keep in mind that component imported with React.lazy should be rendered inside a React.Suspense
- Created At
- 5/24/2019
- Updated At
- 5/21/2022
- Published At
- 5/24/2019