Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Dynamically Import Non-Default Component or Function

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)?

like image 358
Abhinand Shibu Avatar asked Jun 26 '26 23:06

Abhinand Shibu


1 Answers

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'))
like image 178
MrCode Avatar answered Jun 29 '26 11:06

MrCode