Svelte List rendering tutorial

Svelte List rendering tutorial

In this tutorial, we are going to learn about how to render a list of items into the dom.

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

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 value 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 our example code we are using user as an alias to access the id and name we can replace the user to {id, name}

<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