Svelte allows us to loop through a list of data using the #each block. Let’s have a look at this example to understand how it works.
We’re going to add name and email as an object and push it to a list. We’ll then loop through the list of data.
First of all, let’s create a small component that would show a card component. This component woulda accept name and email as props.
<script>
export let name
export let email
</script>
<div>
<div class="crd">
<div class="crd-header">
{name}
</div>
<div class="crd-content">
{email}
</div>
</div>
</div>
<style>
.crd {
max-width: 300px;
max-width: 300px;
max-width: 300px;
border: 2px solid #6100cf;
border-radius: 4px;
padding: 10px;
margin-top: 12px;
background: #fff;
}
.crd-header {
font-size: 18px;
font-weight: bold;
border-bottom: 1px solid #d5d5d5;
padding-bottom: 4px;
}
.crd-content {
font-size: 18px;
padding-top: 4px;
}
</style>
Code language: HTML, XML (xml)
Now we can import this component into our main component and use it. Here’s our main component code:
<script>
import CardComponent from './CardComponent.svelte'
let userName = ''
let userEmail = ''
let users = []
const addUser = () => {
if(userName && userEmail) {
users = [...users, {
name: userName,
email: userEmail
}]
userName = userEmail = ''
}
}
const removeUsers = () => {
users = []
}
</script>
<div>
<input
type="text"
bind:value={userName}
placeholder="Enter name"
class="input-text"
/>
<input
type="text"
bind:value={userEmail}
placeholder="Enter email"
class="input-text"
/>
<button on:click="{addUser}">Add user</button>
<button on:click="{removeUsers}">Delete all</button>
{#each users as user (user.email)}
<CardComponent name={user.name} email={user.email}/>
{/each}
</div>
<style>
.input-text {
font-size: 20px;
outline: none;
margin: 4px 0;
}
</style>
Code language: HTML, XML (xml)
In the above file, we’ve first created an empty list named users on line 7. Then we’ve created a function called addUser to add an object with values { name: userName, email, userEmail } and push it to users array.
We’ve then iterated through the users array on lines 41-43. You’d notice that we’ve used ‘each users as user’ in the #each statement. This allows us to refer to each of the objects on the list. We can call this object whatever we want. In this case, just user. It is worth noticing that we’re not using the push() method. This is because push only adds to the list without changing or updating the reference pointer of the variable. Instead, we’re copying content from the previous list and then populating it again with the previous list content and the new content:
users = [...users, {
name: userName,
email: userEmail
}]
We also have a ‘Delete all’ button which simply calls the deleteUsers method and sets the users array empty.
Here’s what the above example looks like in action: