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.

    let elementArray; 
    // elementArray = div

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

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

    let elementArray = [];
    // elementArray = [div, div, div...]

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