
How to Create Dynamic Components in Svelte
To dynamically render components in Svelte, use the svelte:component
element.
<script>
import ExperimentOne from './ExperimentOne.svelte';
import ExperimentTwo from './ExperimentTwo.svelte';
let component = (Math.random() * 100) > 50 ?
ExperimentTwo :
ExperimentOne;
</script>
<svelte:component this={component} />
Copied to clipboard!
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
Unlimited access to hundred of tutorials
Access to exclusive interactive lessons
Remove ads to learn without distractions