How to Use If Statements in Svelte: Simple Conditional Rendering
In Svelte, use the
{#if} block to conditionally render content based on a condition. Wrap the content inside {#if condition} and close it with {/if}. You can also add {:else} for alternative content.Syntax
The {#if} block in Svelte lets you show or hide parts of your UI based on a condition. You start with {#if condition}, put the content to show if true, optionally add {:else} for the false case, and end with {/if}.
- condition: a JavaScript expression that evaluates to true or false.
- {#if}: starts the conditional block.
- {:else}: optional, defines what to show if the condition is false.
- {/if}: closes the block.
svelte
{#if condition}
<!-- content shown if condition is true -->
{:else}
<!-- content shown if condition is false -->
{/if}Example
This example shows a simple message that changes based on a boolean variable loggedIn. If loggedIn is true, it shows a welcome message; otherwise, it asks the user to log in.
svelte
<script> let loggedIn = false; </script> <button on:click={() => loggedIn = !loggedIn}> Toggle Login State </button> {#if loggedIn} <p>Welcome back, user!</p> {:else} <p>Please log in to continue.</p> {/if}
Output
Button labeled 'Toggle Login State' and below it either 'Please log in to continue.' or 'Welcome back, user!' depending on button clicks.
Common Pitfalls
Common mistakes when using {#if} blocks include:
- Forgetting to close the block with
{/if}, which causes errors. - Using JavaScript statements instead of expressions inside the condition (only expressions work).
- Trying to use
else ifdirectly; instead, nest{#if}blocks inside{:else}for multiple conditions.
svelte
<!-- Wrong: missing {/if} -->
{#if loggedIn}
<p>Welcome!</p>
<!-- Correct: properly closed -->
{#if loggedIn}
<p>Welcome!</p>
{/if}
<!-- Wrong: using else if directly -->
{#if condition1}
<p>One</p>
{:else if condition2}
<p>Two</p>
{/if}
<!-- Correct: nested if inside else -->
{#if condition1}
<p>One</p>
{:else}
{#if condition2}
<p>Two</p>
{/if}
{/if}Quick Reference
Remember these tips when using {#if} in Svelte:
- Use expressions only in conditions.
- Close every
{#if}with{/if}. - Use
{:else}for the false case. - For multiple conditions, nest
{#if}blocks inside{:else}.
Key Takeaways
Use {#if condition} ... {/if} blocks to conditionally render content in Svelte.
Always close your if blocks with {/if} to avoid errors.
Use {:else} for alternative content when the condition is false.
For multiple conditions, nest if blocks inside {:else} instead of else if.
Conditions must be JavaScript expressions, not statements.