Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically render components in Svelte?

Tags:

svelte

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?

like image 635
rohanharikr Avatar asked May 14 '26 12:05

rohanharikr


1 Answers

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

like image 105
CD.. Avatar answered May 19 '26 04:05

CD..



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!