James McGrath

Array of elements from Svelte each block

Oct 02, 2023
1 minute

Since moving from Vue to Svelte one of the things I miss from Vue is when it would create an array of elements using a ref in a v-for loop.

Unfortanately you can’t do this in Svelte. The binded variable will be assigned the last element in the each block.

<script>
    let elementArray; 
    // elementArray = div
</script>

{each items as item } 
    <div bind:this={elementArray}>{item}</div>
{/each}

A small change to that example will produce an array of elements.

<script>
    let elementArray = [];
    // elementArray = [div, div, div...]
</script>

{each items as item, index } 
    <div bind:this={elementArray[index]}>{item}</div>
{/each}