Skip to content

Svelte List Rendering Explained — Each Blocks

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Svelte List Rendering Explained. We cover key concepts, practical examples, and best practices to help you master this topic.

Svelte's {#each} block iterates over arrays and iterable objects, with optional key expressions for efficient DOM updates when lists change.

What You'll Learn

  • Basic {#each} iteration
  • Keyed each blocks for identity
  • Index and destructuring
  • Reactive list filtering
  • Empty state with {:else}

Why It Matters

List rendering is fundamental to dynamic UIs. Keyed each blocks ensure Svelte tracks element identity for efficient updates, preventing unnecessary DOM recreation.

<script>
  let items = [
    { id: 1, name: "Laptop", price: 999 },
    { id: 2, name: "Mouse", price: 25 },
    { id: 3, name: "Keyboard", price: 75 },
  ];

  let filterText = "";

  $: filtered = items.filter(i =>
    i.name.toLowerCase().includes(filterText.toLowerCase())
  );

  function removeItem(id) {
    items = items.filter(i => i.id !== id);
  }

  function addItem() {
    const newId = Math.max(...items.map(i => i.id), 0) + 1;
    items = [...items, { id: newId, name: `Item ${newId}`, price: 0 }];
  }
</script>

<input bind:value={filterText} placeholder="Filter items..." />
<button on:click={addItem}>Add Item</button>

{#each filtered as item, i (item.id)}
  <div>
    <span>{i + 1}. {item.name} — ${item.price}</span>
    <button on:click={() => removeItem(item.id)}>X</button>
  </div>
{:else}
  <p>No items match your filter</p>
{/each}

Expected output: Filtered list with remove capability, add button, empty state when no items match, and efficient keyed updates.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro