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
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: