by Sai gowtham

How to loop over the array in Svelte

In this tutorial, we are going to learn about how to loop over the array in svelte.

Svelte has a special syntax called each block which helps us to render a list of items into the dom.

Example:

List-rendering.svelte
<script>
   let users = [
       {id:1,name: "king"},
       {id:2, name: "gowtham"},
       {id:3, name: "sai"}
      ]
</script>


<ul>
    //users is array and user is an alias
    {#each users as user}       <li>{user.id}</li>
       <li>{user.name}</li>
    {/each}

</ul>

In the above code, we have a users array where user is an alias which is pointing to the different object on each iteration.

each-block-example

Accessing Index

We can also access the index of the item present inside the array.

<ul>{3}
    //users is array and user is an alias
    {#each users as user,index}
       <li>{user.id}</li>
       <li>{user.name}</li>
    {/each}
</ul>

Destructuring

In the above example, we are using the user as an alias to access the object properties id and name, instead of that we can also use the destructuring syntax.

<ul>
  {#each users as { id, name }}    <li>{id}</li>
    <li>{name}</li>
  {/each}
</ul>

Keys

Sometimes we need to remove or update the particular items in the list. In such cases, we need to pass a unique identifier to the each block so that svelte can understands exactly which element you are trying to remove or update.

example:

List-rendering.svelte
<script>
  let users = [
    { id: 1, name: "king" },
    { id: 2, name: "gowtham" },
    { id: 3, name: "sai" }
  ];

  function removeUser(i) {
     users = users.filter((user, i) => i !== index);
  }
</script>

<style>
  li {
    padding: 1rem;
    box-shadow: 1px 1px 1px #0000;
    background-color: royalblue;
    margin-bottom: 1rem;
    color: white;
  }
</style>

<ul>
  <!-- id is unique identifier in our case -->
  {#each users as { id, name }, i (id)}    <li on:click={() => removeUser(i)}> {id} - {name} </li>  {/each}
</ul>

svelte-removing-items-example

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course