0
0
Svelteframework~30 mins

Use directive syntax in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Use directive syntax in Svelte
📖 Scenario: You are building a simple Svelte app that shows a list of tasks. You want to display only the tasks that are marked as important.
🎯 Goal: Create a Svelte component that uses the {#if} directive to show only important tasks from a list.
📋 What You'll Learn
Create an array called tasks with objects containing id, name, and important properties
Create a boolean variable called showImportantOnly set to true
Use the {#if} directive inside a {#each} block to display only tasks where important is true when showImportantOnly is true
Add a button that toggles showImportantOnly between true and false
💡 Why This Matters
🌍 Real World
Filtering lists based on user preferences is common in apps like to-do lists, shopping lists, and email clients.
💼 Career
Understanding Svelte directives and reactive variables is essential for building interactive web apps efficiently.
Progress0 / 4 steps
1
Create the tasks array
Create an array called tasks with these exact objects: { id: 1, name: 'Buy groceries', important: true }, { id: 2, name: 'Clean room', important: false }, and { id: 3, name: 'Pay bills', important: true }.
Svelte
Hint

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

2
Add the showImportantOnly variable
Add a boolean variable called showImportantOnly and set it to true.
Svelte
Hint

Use let showImportantOnly = true; to create the variable.

3
Use {#each} and {#if} directives to show tasks
Use a {#each tasks as task} block to loop over tasks. Inside it, use a {#if} directive to show the task.name only if showImportantOnly is false or if task.important is true.
Svelte
Hint

Use {#each tasks as task} to loop, then inside use {#if !showImportantOnly || task.important} to conditionally show the task name.

4
Add a button to toggle showImportantOnly
Add a <button> element that toggles the showImportantOnly variable between true and false when clicked. Use the on:click directive with a function that sets showImportantOnly = !showImportantOnly. The button text should be Toggle Important Only.
Svelte
Hint

Use <button on:click={() => showImportantOnly = !showImportantOnly}> with the exact toggle logic.