0
0
Svelteframework~30 mins

Keyed each blocks in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Keyed Each Blocks in Svelte
📖 Scenario: You are building a simple Svelte app that shows a list of tasks. Each task has a unique ID and a name. You want to display these tasks in a way that Svelte can track each item efficiently when the list changes.
🎯 Goal: Create a Svelte component that uses a keyed {#each} block to render a list of tasks. Each task should have a unique id used as the key.
📋 What You'll Learn
Create an array of task objects with exact IDs and names
Add a variable to hold the number of tasks
Use a keyed {#each} block with task.id as the key
Render each task's name inside a <li> element
💡 Why This Matters
🌍 Real World
Keyed each blocks help Svelte track list items efficiently when items are added, removed, or reordered, improving performance and user experience in dynamic lists.
💼 Career
Understanding keyed each blocks is essential for building interactive user interfaces in Svelte, a popular modern frontend framework used in web development jobs.
Progress0 / 4 steps
1
Create the tasks array
Create a variable called tasks that is an array with these exact objects: { id: 1, name: 'Wash dishes' }, { id: 2, name: 'Do laundry' }, and { id: 3, name: 'Take out trash' }.
Svelte
Need a hint?

Use let tasks = [ ... ] with the exact objects inside the array.

2
Add a variable for task count
Create a variable called taskCount and set it to the length of the tasks array.
Svelte
Need a hint?

Use let taskCount = tasks.length; to get the number of tasks.

3
Use a keyed each block to render tasks
Write a Svelte {#each} block that loops over tasks using task.id as the key. Inside the block, render each task.name inside an <li> element.
Svelte
Need a hint?

Use {#each tasks as task (task.id)} to start the keyed each block and close it with {/each}.

4
Add a heading showing the task count
Add an <h2> element above the list that displays the text Task count: followed by the taskCount variable.
Svelte
Need a hint?

Use <h2>Task count: {taskCount}</h2> above the list.