The svelte:component tag lets you show different components based on a variable. It helps when you want to switch parts of your page without writing many if-else blocks.
0
0
svelte:component for dynamic components
Introduction
You want to show different UI parts based on user choices.
You have a list of components and want to pick one to display dynamically.
You want to load components conditionally without repeating code.
You build a dashboard where widgets change based on settings.
Syntax
Svelte
<svelte:component this={ComponentVariable} {...props} />this attribute must be a component reference (not a string).
You can pass props to the dynamic component using spread syntax or named props.
Examples
Shows the
Button component dynamically.Svelte
<script> import Button from './Button.svelte'; let current = Button; </script> <svelte:component this={current} />
Switches between
RedBox and BlueBox components and passes a size prop.Svelte
<script> import RedBox from './RedBox.svelte'; import BlueBox from './BlueBox.svelte'; let box = RedBox; </script> <svelte:component this={box} size="large" />
Randomly shows either
Hello or Goodbye component with a name prop.Svelte
<script> import Hello from './Hello.svelte'; import Goodbye from './Goodbye.svelte'; let greet = Math.random() > 0.5 ? Hello : Goodbye; </script> <svelte:component this={greet} name="Friend" />
Sample Program
This example shows a button that switches between Cat and Dog components when clicked. The displayed component changes dynamically.
Svelte
<script> import Cat from './Cat.svelte'; import Dog from './Dog.svelte'; let animal = Cat; function toggle() { animal = animal === Cat ? Dog : Cat; } </script> <button on:click={toggle} aria-label="Toggle animal">Toggle Animal</button> <svelte:component this={animal} />
OutputSuccess
Important Notes
Make sure the variable used in this is a valid Svelte component.
You can pass any props to the dynamic component just like a normal component.
Use svelte:component to avoid many if-else blocks and keep code clean.
Summary
svelte:component lets you render components dynamically based on a variable.
Use the this attribute to specify which component to show.
You can pass props to the dynamic component as usual.