How to Create Dynamic Components in Svelte
To dynamically render components in Svelte, use the svelte:component
element.
Copied to clipboard!
<script>
import ExperimentOne from './ExperimentOne.svelte';
import ExperimentTwo from './ExperimentTwo.svelte';
let component = (Math.random() * 100) > 50 ?
ExperimentTwo :
ExperimentOne;
</script>
<svelte:component this={component} />
You can pass the component to render as the this
property. Whenever its value changes, the component is destroyed and then recreated. If this
is falsy, no component will be rendered.
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews