Svelte 7: List Rendering
easy⏱ 5 mincoursesvelte
{#each} with a key
The three parts of {#each todos as todo, i (todo.id)} each do a distinct job: todo is the current element, i is its index (handy for numbering, not for identity), and (todo.id) is the key Svelte uses to track which rendered <li> belongs to which data object as the array changes.
{#each todos as todo, i (todo.id)}
<li>{i + 1}. {todo.text}</li>
{/each}
Why keys matter
Imagine a list of todos each with its own checkbox, unkeyed. Delete the first todo, and Svelte — matching by position only — keeps the DOM node that was rendering row 1 but now shows row 2's data, including whatever checked state was already sitting on that checkbox. A stable (todo.id) key tells Svelte the identity moved, not the content, so it moves the actual node instead of reinterpreting it.
Build TodoList
Render the todos array with {#each todos as todo, i (todo.id)}, number each row with i + 1, and add a button that pushes a new object into the $state array.