How to dynamically render components in Svelte?
Asked Answered
E

1

6

I'm trying to loop through an array to render the component with the value of type.

<script>

import One from './One.svelte';    
import Two from './Two.svelte';
import Three from './Three.svelte';

const contents = [
 {type: 'One'},
 {type: 'Two'},
 {type: 'Three'},
 {type: 'One'}
]

</script>

{#each contents as content}
    <{content.type} />
{/each}

Desired output:

<One />
<Two />
<Three />
<One />

What is the best way to do this?

Enchase answered 10/1, 2021 at 17:47 Comment(0)
T
11

Use <svelte:component>:

The <svelte:component> element renders a component dynamically, using the component constructor specified as the this property. When the property changes, the component is destroyed and recreated.

For example:

<script>
    import One from './One.svelte';    
    import Two from './Two.svelte';

const contents = [
 One,
 Two
]
</script>

{#each contents as content}
    <svelte:component this={content}/>
{/each}

https://svelte.dev/repl/e56e75ad9b584c44930fe96489a36e14?version=3.31.2

Teahouse answered 10/1, 2021 at 18:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.