Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Import and Lazy load React Components

I am trying to load a components inside of a Tab component for react. The Idea is have a json ( or better yaml) with this syntanx:

interface TabType {
    name: string;
    components: string[];
}

interface Templates {
    tabs: TabType[];
}

const templateTabsModules: Templates = {
    tabs: [
        {
            name: "Title for Tab 1",
            components: ["./components/OneComponent"]
        },
        {
            name: "Title for Tab 2",
            components: ["./components/TwoComponent"]
        }
    ]
};

So inside of the Main Component do something like:

<Tabs id="tab">
   {templateTabsModules.tabs.map(tab => {
      return (
        <Tab title={tab.name}>
          <p>The component should appears bellow:</p>
          <Suspense fallback={<div>Loading</div>}>
           {tab.components.map(component => {
              const Comp = lazy(() => import(component));
              return (<Comp />)
           })}
          </Suspense>
         </Tab>
       );
    })}
</Tabs>

But this code does not work, I could see that if I use just the path as string by doing const Comp = lazy(() => import('./components/OneComponent')); it works, but does not if I use the dynamic variable.

like image 937
Rubén Fanjul Estrada Avatar asked Aug 27 '19 07:08

Rubén Fanjul Estrada


1 Answers

I found a possible solution that does what I need without declare before the components by doing:

<Tabs id="tab">
  {templateTabsModules.tabs.map((tab, index) => {
     return (
        <Tab title={tab.name} key={index}>
            <p>The component should appears bellow:</p>
            <Suspense fallback={<div>Loading</div>}>
             tab.components.map(component => {
               const Comp = lazy(() => import(
                 /* webpackChunkName: "my-chunk-name" */
                 /* webpackMode: "lazy" */
                 `${component}`
               ).then(comp => comp));

               return (<Comp />)

             })}
            </Suspense>
        </Tab>
      );
   })}
</Tabs>

So Webpack can load the component and return it as promise

Example -> https://codesandbox.io/s/lazy-components-with-react-mix9y

like image 124
Rubén Fanjul Estrada Avatar answered Sep 21 '22 01:09

Rubén Fanjul Estrada