0

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;
Seona Sim
  • 69
  • 6
  • Have never tried but I don't think there's any reason it shouldn't work, but this won't be useful at all coz you have imported all components which defeats the purpose of dynamic component. – prograk Mar 07 '22 at 09:49

1 Answers1

1

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

Taxel
  • 3,859
  • 1
  • 18
  • 40