How to Use {#if} Block in Svelte: Simple Conditional Rendering
In Svelte, use the
{#if} block to conditionally show content based on a JavaScript expression. Wrap the content inside {#if condition} and close it with {/if}. You can add {:else} to show alternative content when the condition is false.Syntax
The {#if} block starts with {#if condition}, where condition is any JavaScript expression that returns true or false. The block ends with {/if}. You can optionally add {:else} inside to show content when the condition is false.
- {#if condition}: Start the block with a condition.
- {:else}: Optional, shows content if condition is false.
- {/if}: Ends the block.
svelte
<!-- Basic if block syntax --> {#if condition} <!-- content shown if condition is true --> {:else} <!-- content shown if condition is false --> {/if}
Example
This example shows a button that toggles a message. When showMessage is true, the message appears. Otherwise, a different message is shown.
svelte
<script> let showMessage = false; function toggle() { showMessage = !showMessage; } </script> <button on:click={toggle} aria-pressed={showMessage}> Toggle Message </button> {#if showMessage} <p>The message is visible!</p> {:else} <p>The message is hidden.</p> {/if}
Output
Button labeled 'Toggle Message'. When clicked, text toggles between 'The message is visible!' and 'The message is hidden.'
Common Pitfalls
Common mistakes include forgetting to close the {#if} block with {/if}, or using invalid JavaScript expressions inside the condition. Also, avoid putting complex logic directly in the condition; instead, use variables for clarity.
Example of wrong and right usage:
svelte
<!-- Wrong: Missing {/if} -->
{#if show}
<p>Shown</p>
<!-- Right: Properly closed -->
{#if show}
<p>Shown</p>
{/if}Quick Reference
| Syntax | Description |
|---|---|
| {#if condition} | Start conditional block, show content if true |
| {:else} | Optional, show content if condition is false |
| {/if} | End the conditional block |
Key Takeaways
Use {#if condition} ... {/if} to show content only when the condition is true.
Add {:else} inside the block to show alternative content when the condition is false.
Always close the {#if} block with {/if} to avoid errors.
Keep conditions simple and use variables for complex logic.
Use accessible attributes like aria-pressed on interactive elements.