I've seen that we can dynamically import default components using:
const MyComponent = React.lazy(() => import('./myPath'));
We can render it just by using <MyComponent/>. To my understanding this method only allows for the importing of default components from the specified path.
My question is: How can we dynamically import other components or functions that are exported from myPath (non default)?
React.lazy currently supports only default exports. A suggested solution from the docs is:
If the module you want to import uses named exports, you can create an intermediate module that reexports it as the default. This ensures that tree shaking keeps working and that you don’t pull in unused components.
For example
// ManyComponents.js
export const MyComponent = /* ... */;
export const MyUnusedComponent = /* ... */;
// MyComponent.js
export { MyComponent as default } from "./ManyComponents.js";
// MyApp.js
import React, { lazy } from 'react';
const MyComponent = lazy(() => import("./MyComponent.js"));
Another solution is some added boilerplate like below. This way, there is no need for an intermediary component:
const MyComponent = React.lazy(() =>
import('./MyComponent').then((module) => ({ default: module.MyComponent }))
)
Alternately, you can use react-lazily like so:
const { MyComponent } = lazily(() => import('./MyComponent'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With