I want to load a component dynamically based on the route. I\'m trying to make a single page which can load any individual component for testing purposes.
However whe
I had the same issue like the thread opener.
The Documentation describe, that it's not possible to use template strings in the import()
inside dynamic:
In my case it was also impossible to add an general variable with the path there...
I've found an easy trick to solve this issue:
// getComponentPath is a method which resolve the path of the given Module-Name
const newPath = `./${getComponentPath(subComponent)}`;
const SubComponent = dynamic(() => import(''+newPath));
All the MAGIC seems to be the concatenation of an empty String with my generated Variable newPath
: ''+newPath
Another Solution (posted by bjn from the nextjs
-Discord-Channel):
const dynamicComponents = {
About: dynamic(() => import("./path/to/about")),
Other: dynamic(() => import("./path/to/other")),
...
};
// ... in your page or whatever
const Component = dynamicComponents[subComponent];
return
This example might be useful, if you know all dynamically injectable Components. So you can list them all and use it later on in your code only if needed)