Discover how a few simple directives can transform your web code from messy to magical!
Why Use directive syntax in Svelte? - Purpose & Use Cases
Imagine you want to show or hide parts of your webpage based on user actions, like clicking a button or typing in a box, and you try to do this by manually changing the HTML or CSS every time.
Manually updating the page elements is slow and confusing. You have to write lots of code to check states and update the page, which can easily cause mistakes and make your code messy.
Svelte's directive syntax lets you write simple, clear instructions right in your HTML to control behavior like showing, hiding, or reacting to events automatically, making your code cleaner and easier to understand.
const button = document.querySelector('button'); button.addEventListener('click', () => { const box = document.querySelector('#box'); if (box.style.display === 'none') { box.style.display = 'block'; } else { box.style.display = 'none'; } });
<script>
let show = false;
</script>
<button on:click={() => show = !show}>Toggle</button>
{#if show}
<div id="box">Content</div>
{/if}You can build interactive web pages that update instantly and cleanly without writing complex manual code.
Think of a shopping site where clicking a product shows more details instantly without reloading the page or writing complicated JavaScript.
Manual DOM updates are slow and error-prone.
Directive syntax lets you write clear, automatic UI behavior.
It makes your code simpler and your app more responsive.
Practice
{#if}, {#each}, on:, or bind:?Solution
Step 1: Understand the purpose of
The{#if}{#if}directive in Svelte shows or hides content based on a condition.Step 2: Compare with other directives
{#each}loops over lists,on:handles events, andbind:links variables to inputs.Final Answer:
{#if}-> Option BQuick Check:
Conditional display ={#if}[OK]
- Confusing {#if} with {#each} for loops
- Using on:click for conditional display
- Trying to bind variables for conditionals
Solution
Step 1: Recall Svelte event directive syntax
Svelte useson:eventName={handler}to listen to events like clicks.Step 2: Check each option
<button on:click={handleClick}>Click</button>useson:clickcorrectly. Options A, B, and D use incorrect or invalid syntax.Final Answer:
<button on:click={handleClick}>Click</button> -> Option CQuick Check:
Event listener syntax = on:event [OK]
- Using camelCase like onClick instead of on:click
- Trying to bind events with bind:
- Omitting the on: prefix
<script>
let items = ['apple', 'banana'];
</script>
<ul>
{#each items as item}
<li>{item}</li>
{/each}
</ul>Solution
Step 1: Understand the {#each} directive
The {#each} directive loops over the arrayitemsand assigns each element toitem.Step 2: Render list items
For eachitem, it creates a <li> element with the item text inside.Final Answer:
<ul><li>apple</li><li>banana</li></ul> -> Option AQuick Check:
Loop items render as list =- apple
- banana
- Expecting the literal string {item} to show
- Confusing the array name with item variable
- Thinking it causes a syntax error
<script>
let count = 0;
</script>
<button on:click="count++">Increment</button>
<p>Count: {count}</p>Solution
Step 1: Check event handler syntax
Svelte requires event handlers to use curly braces without quotes:on:click={count++}.Step 2: Identify the error
The code uses quotes around the expression, which causes a syntax error.Final Answer:
Using double quotes around the event handler expression -> Option AQuick Check:
Event handler must be unquoted expression [OK]
- Putting event handler code inside quotes
- Trying to bind variables unnecessarily
- Assuming variable name is wrong
done property?Solution
Step 1: Understand binding checkbox state
In Svelte,bind:checkedlinks the checkbox's checked state directly to a variable, updating it automatically.Step 2: Analyze each option
<script> let tasks = [ { id: 1, text: 'Task 1', done: false }, { id: 2, text: 'Task 2', done: true } ]; </script> <ul> {#each tasks as task} <li> <input type="checkbox" bind:checked={task.done} /> {task.text} </li> {/each} </ul>usesbind:checked={task.done}, which is correct.<ul> {#each tasks as task} <li> <input type="checkbox" checked={task.done} on:change={() => task.done = !task.done} /> {task.text} </li> {/each} </ul>manually toggles on change but is more complex.<ul> {#each tasks as task} <li> <input type="checkbox" bind:value={task.done} /> {task.text} </li> {/each} </ul>usesbind:valuewhich is incorrect for checkboxes.<ul> {#each tasks as task} <li> <input type="checkbox" on:click={task.done = !task.done} /> {task.text} </li> {/each} </ul>uses on:click without binding, which is less reactive.Final Answer:
bind:checked={task.done} -> Option DQuick Check:
Checkbox bind:checked updates variable automatically [OK]
- Using bind:value instead of bind:checked for checkboxes
- Manually toggling state instead of binding
- Using on:click without reactive binding
Ready to prove it?
Pass the test and this pattern moves unknown
