0 day streak
javascript / beginner
Snippet

Updating Reactive Arrays with the Spread Operator

Svelte relies on assignment to trigger reactivity. Using the spread operator to create a new array reference ensures the UI automatically re-renders when adding elements.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
let fruits = ['Apple', 'Banana'];
function addFruit(newFruit) {
fruits = [...fruits, newFruit];
}
</script>
<button on:click={() => addFruit('Orange')}>Add Orange</button>
<ul>
{#each fruits as fruit}
<li>{fruit}</li>
{/each}
</ul>
svelte
Breakdown
1
fruits = [...fruits, newFruit];
Creates a new array containing existing items plus the new item and reassigns it to trigger reactivity.
2
{#each fruits as fruit}
Iterates over the updated reactive array to render each list item.