Call class dynamically by name (string to class name)
I’m making a very simple router in Svelte. Pages are imported as components by passing currentHash (ex: /#Dashboard
):
import Dashboard from './Dashboard.svelte'; import About from './About.svelte'; import NotFound from './404.svelte'; let component = currentHash; // 'Dashboard' as string
Later, I’m loading the component using the following:
<svelte:component this={component} />
That doesn’t work as this function doesn’t take String but the class itself.
The only thing that works is let component = eval(currentHash);
and it works but I don’t want to use eval
.
Also, tired component = window[currentHash]
; and that doesn’t work either.
How do I convert a String variable to Class call?
Answer
You will need to know all possible components that could be rendered and implement a mapping yourself
<script> import Dashboard from './Dashboard.svelte'; import About from './About.svelte'; import NotFound from './404.svelte'; const componentMap = { Dashboard, About, NotFound } let component = currentHash; </script> <svelte:component this={componentMap[currentHash]} />