svelte

How to dynamically render components in 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?


Solution

  • 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