Home > database >  can i use dynamic import with for loop in next.js?
can i use dynamic import with for loop in next.js?

Time:03-07

I'm going to use dynamic import when I need to bring in a lot of components. In this situation, is it possible to use 'for' loop?

import dynamic from "next/dynamic";

let Dynamic = [];

for (let i = 1; i < 80; i  ) {
  const DynamicComponent = dynamic(() =>
    import(`../src/Templates/BlendyTemplate${i}`)
  );
  Dynamic.push(DynamicComponent);
}

//this is just example..
const Home = () =>{

const [state,setState] = useState(0);

let DynamicComponents = Dynamic[state]

return <div>
<button onClick={()=>{setState(state 1)}}
<DynamicComponents/></div>
}

export default Home;

CodePudding user response:

No you cannot generate the path dynamically:

Note: In import('path/to/component'), the path must be explicitly written. It can't be a template string nor a variable. Furthermore the import() has to be inside the dynamic() call for Next.js to be able to match webpack bundles / module ids to the specific dynamic() call and preload them before rendering. dynamic() can't be used inside of React rendering as it needs to be marked in the top level of the module for preloading to work, similar to React.lazy.

source

CodePudding user response:

This is one of the best answers I could have found so far for you.

https://stackoverflow.com/a/65442708

Technically, import() only supports static paths. The main reason for it is mostly from Webpack's compiler which does not understand dynamic paths.

But we still have a few workarounds for it.

This is one of the solutions I tried locally and it worked (without warnings)

const dynamicComponents = {
  About: dynamic(() => import("./path/to/about")),
  Other: dynamic(() => import("./path/to/other")),
  ...
};

const Component = dynamicComponents[subComponent];
return <Component />
  • Related