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:
<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.
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:
<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>