Svelte For Each Block Loop Example

Svelte For Each Block Loop Example

05/22 By frontendshape

Hello everyone in today section, we will see how to use for each block loop in svelte. Svelte each block loop is very simple it start with {#each } and end with {/each}. before we start you should install svelte first.

How to install & setup Vite + Typescript in Svelte


Svelte For Each Block Loop Example

1. Svelte simple each block loop.

<script>
	let people = ['Jone Doe', 'Watson', 'Dennis'];
</script>

<ul>
	{#each people as person}
		<li>Name: {person}</li>
	{/each}
</ul>
svelte each loop

svelte each loop

2. with each loop with index

<script>
	let people = ['Jone Doe', 'Watson', 'Dennis'];
</script>

<ul>
	{#each people as person, index}
		<li>{index}) Name: {person}</li>
	{/each}
</ul>

<style>
	ul{
		text-align: center;
		list-style: none;
	}
</style>
svelte each loop with index

svelte each loop with index

3. Svelte each loop with keyed object

<script>
	let people = [{id: 1, name: 'Jone Doe'}, {id: 2, name:'Watson'}, {id: 3, name:'Dennis'}];
</script>

<ul>
	{#each people as person, index(person.id)}
		<li>{person.id}) Name: {person.name}</li>
	{/each}
</ul>

<style>
	ul{
		text-align: center;
		list-style: none;
	}
</style>
svelte each block loop with key value

svelte each block loop with key value


Enter Your Search Query