Skip to content

Latest commit

 

History

History
38 lines (31 loc) · 974 Bytes

File metadata and controls

38 lines (31 loc) · 974 Bytes
title
<svelte:component>

A component can change its type altogether with <svelte:component>. In this exercise, we want to show RedThing.svelte if the color is red, GreenThing.svelte if it's green, and so on.

We could do this with a sequence of if blocks...

/// file: App.svelte
{#if selected.color === 'red'}
	<RedThing/>
{:else if selected.color === 'green'}
	<GreenThing/>
{:else if selected.color === 'blue'}
	<BlueThing/>
{/if}

...but it's a little cumbersome. Instead, we can create a single dynamic component:

/// file: App.svelte
<select bind:value={selected}>
	{#each options as option}
		<option value={option}>{option.color}</option>
	{/each}
</select>

---{#if selected.color === 'red'}
	<RedThing />
{:else}
	<p>TODO others</p>
{/if}---
+++<svelte:component this={selected.component} />+++

The this value can be any component constructor, or a falsy value — if it's falsy, no component is rendered.