Svelte.js 3 each Iteration Rendering Tutorial

In this Svelte tutorial we learn how to iterate over lists of data and output their content in the markup.

We cover the each loop, key expression and combining conditional rendering with iteration rendering.

Lesson Project

If you want to follow along with the examples in this lesson, you’ll need a Svelte app that was cloned with degit or scaffolded with Vite

If you already have an app from previous lessons, you can use that instead.

What is Iteration Rendering in Svelte?

We can control the flow of our application by looping through a list of items and rendering elements for each item in the list.

For example, let’s say we want to create an app with a list of the latest films. We want each list item to be a card with the film name, description, image and a link to its dedicated page.

It would be inefficient to create a card manually each time we add a film. Instead, we want to create a template of what the card should look like, then let Svelte render the card for each film in the list and automatically fill in the details from the data.

How to loop through a list in Svelte

The each iteration block allows us to loop through elements in an iterable list, like an array.

An each block is made up of open-and-close blocks. Between those blocks we specify the elements we want to render.

The opening block uses #each , followed by a Svelte specific loop wrapped in curly braces. The closing block is just /each wrapped in curly braces.

Svelte uses a custom as loop that’s similar to a Javascript for..in loop.

Syntax: #each
{#each list as alias}
  <!-- elements to render -->
{/each}

Let’s understand the syntax.

  • list is our iterable list of items, like an array.
  • alias is an alias that refers to the current list item in the loop.

The list must have the same name as the list we define in the script section, but alias can be named whatever we want.

To demonstrate, let’s create an array with two names and loop through them in a paragraph.

Example: src/App.svelte
<script>
  const users = ['John', 'Jane']
</script>

{#each users as user}
  <p>{user}</p>
{/each}

Each time the loop runs, it will create a new paragraph and populate it with the next item in the array where we specify the alias.

How to get the index of a list item in Svelte

Svelte makes it really simple to get the index of an item in our list.

To do that, we add the index after the alias and separate the two with a comma. From there we can use the index like the alias.

Syntax: #each index
{#each list as alias, index}
  <!-- elements to render -->
{/each}

To demonstrate, let’s add an index to our earlier example.

Example: src/App.svelte
<script>
  const users = ['John', 'Jane']
</script>

{#each users as user, index}
  <p>({index}) {user}</p>
{/each}

When we run the example in the browser, we should see a number in front of each user’s name.

A Javascript index always starts at 0 so if we want the numbers to display correctly, we’ll have to add a 1 to the index.

Example: src/App.svelte
<script>
  const users = ['John', 'Jane']
</script>

{#each users as user, index}
  <p>({index + 1}) {user}</p>
{/each}

If we save and take a look in the browser, the numbers show correctly.

How to loop through a list of objects in Svelte

Looping through a list of objects is the same as looping through a list. The only difference is that we access object properties through the alias with dot notation.

Syntax: #each object
{#each list as alias}
  <!-- alias.property -->
{/each}

To demonstrate, let’s change our example from an array to an array of objects. Each object will hold the user’s first and last names as properties.

Example: src/App.svelte
<script>
  const users = [
    { firstName: 'John', lastName: 'Doe' },
    { firstName: 'Jane', lastName: 'Roe' }
  ]
</script>

{#each users as user, index}
  <p>({index}) {user.firstName} {user.lastName}</p>
{/each}

When we run the example in the browser, each user displays their first and last name.

The key expression in Svelte

When we loop through a list, Svelte keeps track of the elements it iterates over with its own internal index. When changes are made to the elements, Svelte will replace their positions in the DOM according to their indexes, not their values.

This can cause problems in the behavior of our application, so Svelte allows us to use to a unique key to give each element a unique ID.

To do that, we add a unique value from the list item in parentheses at the end of the loop.

note We don’t separate the key from the looping statement with a comma.

Syntax: unique key
{#each list as alias, index (unique_key)}
  <!-- elements to render -->
{/each}

To demonstrate, let’s add an ID property to our example and use it as the key for the loop.

Example: src/App.svelte
<script>
  const users = [
    { id: 1, firstName: 'John', lastName: 'Doe' },
    { id: 2, firstName: 'Jane', lastName: 'Roe' }
  ]
</script>

{#each users as user, index (user.id)}
  <p>({index}) {user.firstName} {user.lastName}</p>
{/each}

When we run the example in the browser, nothing changed and we still see the users in their paragraphs.

The difference is behind the scenes.

  • Without keys, Svelte tries to minimize element moving. It tries to patch or reuse elements of the same type, in-place, as much as possible.
  • With keys, Svelte can identify nodes with the unique id when diffing the new DOM tree with the old DOM tree.

Keys are important to handle UI updates correctly and efficiently. Although it’s not required, it’s good practice to always use a key.

How to use an 'if' block inside an 'each' loop

Svelte allows us to use conditional rendering blocks inside our loops. There’s nothing special we need to do, we can just create a conditional block inside an each block.

Syntax: if inside each
{#each list as alias, index (unique_key)}

  {#if condition}
    <!-- has access to alias & index -->
  {/if}

{/each}

Anything inside the each block will have access to both the alias and the index, so we can use them in the conditional block.

As an example, let’s color the text of our first user by using an if..else block.

Example: src/App.svelte
<script>
  const users = [
    { id: 1, firstName: 'John', lastName: 'Doe' },
    { id: 2, firstName: 'Jane', lastName: 'Roe' }
  ]
</script>

{#each users as user, index (user.id)}
  {#if user.id === 1}
    <p class="first">({index}) {user.firstName} {user.lastName}</p>
  {:else}
    <p>({index}) {user.firstName} {user.lastName}</p>
  {/if}
{/each}

<style>
  .first {color:blue;}
</style>

If we save the file and take a look in the browser, the “John Doe” user should be blue.