0 day streak
javascript / intermediate
Snippet

Dynamic Rendering with svelte:component

The <svelte:component> element allows you to render a component dynamically based on a variable. The 'this' property specifies which component constructor to use, making it ideal for tabs, modals, or dynamic dashboards.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
<script>
import RedCard from './RedCard.svelte';
import BlueCard from './BlueCard.svelte';
let current = RedCard;
</script>
<button on:click={() => current = (current === RedCard ? BlueCard : RedCard)}>
Toggle Component
</button>
<svelte:component this={current} />
svelte
Breakdown
1
import RedCard from './RedCard.svelte';
Imports the component definition as a variable.
2
<svelte:component this={current} />
Renders the component currently stored in the 'current' variable.