0 day streak
javascript / beginner
Snippet

Conditional Rendering with {#if}

To conditionally render HTML in Svelte, you use the `{#if}` block. Unlike standard JavaScript `if` statements, these blocks are part of the template and reactively show or hide elements based on the truthiness of the expression.

snippet.js
javascript
1
2
3
4
5
{#if user.loggedIn}
<button>Log Out</button>
{:else}
<button>Log In</button>
{/if}
svelte
Breakdown
1
{#if user.loggedIn}
Starts the conditional block; renders the following content if user.loggedIn is true.
2
{:else}
Defines what to render if the initial condition is false.