How to Create Dynamic Components in Svelte

How to Create Dynamic Components in Svelte

Ferenc Almasi β€’ πŸ”„ 2022 June 01 β€’ πŸ“– 1 min read
  • twitter
  • facebook

To dynamically render components in Svelte, use the svelte:component element.

  import ExperimentOne from './ExperimentOne.svelte';
  import ExperimentTwo from './ExperimentTwo.svelte';

  let component = (Math.random() * 100) > 50 ? 
    ExperimentTwo :

<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.

How to Dynamically Render Components in Svelte
If you would like to see more Webtips, follow @flowforfrank

Looking into SvelteΒ 3
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro