How to loop over the array in Svelte
In this post we will give you information about How to loop over the array in Svelte. Hear we will give you detail about How to loop over the array in SvelteAnd how to use it also give you demo for it if it is necessary.
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 ofitems 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<span>, 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>
Hope this code and post will helped you for implement How to loop over the array in Svelte. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs