How to Use Loops in Svelte

How to Use Loops in Svelte

Ferenc Almasi β€’ Last updated 2020 September 12 β€’ Read time 2 min read
  • twitter
  • facebook

In Svelte, you can iterate through a list using the each template expression:

Copied to clipboard!
<h1>Recipe</h1>
<ul>
    {#each ingredients as ingredient}
        <li>{ingredient.name} ({ingredient.amount})</li>
    {/each}
</ul>
Each.svelte

Just as you would in other well-known frameworks, you can also specify the index as a second parameter:

Copied to clipboard!
{#each ingredients as ingredient, index}
    <li>
        #{index + 1}:
        {ingredient.name} ({ingredient.amount})
    </li>
{/each}
Each.svelte

Next to the index, you can also specify a key which identifies each list item:

Copied to clipboard!
{#each ingredients as ingredient, index (ingredient.id)}
    <li>
        #{index + 1}:
        {ingredient.name} ({ingredient.amount})
    </li>
{/each}
Each.svelte

If a key is provided, Svelte will diff changes, instead of removing or adding items at the end of the list. Svelte also allows the use of destructuring inside each blocks:

Copied to clipboard!
{#each ingredients as { name, amount }, index (ingredient.id)}
    <li>
        #{index + 1}:
        {name} ({amount})
    </li>
{/each}
Each.svelte

It also let's you use the spread operator:

Copied to clipboard!
{#each ingredients as { ...props }}
    <Ingredient {...props} />
{/each}
Each.svelte

You can also specify an else clause. In case you don't have any elements inside the list, the content inside it will be displayed instead:

Copied to clipboard!
{#each ingredients as ingredient}
    <li>{ingredient.name} ({ingredient.amount})</li>
{:else}
    <li>Looks like this will be a cheap dinner 🍲</li>
{/each}
Each.svelte
Loops in Svelte
If you would like to see more Webtips, follow @flowforfrank

Looking into Svelte 3

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.