πŸŽ„ Get 50% off from our JavaScript course for the holidays! πŸŽ„
How to Create Dynamic Components in Svelte

How to Create Dynamic Components in Svelte

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

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} />
Dynamic.svelte
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 to improve your skills? Check out our interactive course to master JavaScript from start to finish.
JavaScript Course
Looking into SvelteΒ 3
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More

Recommended

πŸŽ‰ Thank you for subscribing to our newsletter. x