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...
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:
App.svelte
<select bind:value={selected}>
{#each options as option}
<option value={option}>{option.color}</option>
{/each}
</select>
<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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<script>
import RedThing from './RedThing.svelte';
import GreenThing from './GreenThing.svelte';
import BlueThing from './BlueThing.svelte';
const options = [
{ color: 'red', component: RedThing },
{ color: 'green', component: GreenThing },
{ color: 'blue', component: BlueThing }
];
let selected = options[0];
</script>
<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}