Reputation: 79
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;
Upvotes: 0
Views: 1460
Reputation: 4197
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.
Upvotes: 1