I am trying to dynamically import components at runtime based on configuration provided in data.
I have created a DynamicComponant that accepts a component identifier and its associated props object, which then looks up the component path and attempts to dynamically load it and pass it its props.
type Props = {
id: string,
dynamicProps: Record<string, any>
}
const DynamicComponent = (props: Props) => {
const {id, dynamicProps} = props;
const [Component, setComponent] = useState<ReactNode | null>(null);
const loadComponent = async (componentName: string) => {
const config = componentConfig.find((c) => c.name === componentName);
if (config) {
const Component = dynamic(() => import(config.importPath));
setComponent(<Component {...dynamicProps} />);
} else {
setComponent(null);
}
};
useEffect(() => {
loadComponent(id);
},[id]);
return (
<Suspense fallback={<div>Loading...</div>}>
{Component}
</Suspense>
)
};
With this I get the Error: Cannot find module ‘[component path]’
However, If I substitute config.importPath with a hardcoded path that matches the one being passed to it, it works and renders the component as expected.
What am I doing wrong?