javascript / beginner
Snippet
Conditional UI State Switching Using Svelte If-Else Blocks
In Svelte, conditional control flow in the markup is handled declaratively using {#if}, {:else}, and {/if} blocks. Instead of writing imperative DOM manipulation in JavaScript, the template responds automatically whenever boolean state variables change.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script>let isLoggedIn = false;function toggleAuth() {isLoggedIn = !isLoggedIn;}</script><button on:click={toggleAuth}>{isLoggedIn ? 'Log Out' : 'Log In'}</button>{#if isLoggedIn}<p>Welcome back, authorized user!</p>{:else}<p>Please log in to access your dashboard.</p>{/if}
svelte
Breakdown
1
let isLoggedIn = false;
Declares a boolean state variable to track authentication status.
2
isLoggedIn = !isLoggedIn;
Toggles the boolean value between true and false on user action.
3
{#if isLoggedIn}
Opens a conditional block that renders child elements only when isLoggedIn is truthy.
4
{:else}
Specifies a fallback template branch rendered when the condition evaluates to false.