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;

1
  • 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. Commented Mar 7, 2022 at 9:49

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.