0
0
Svelteframework~5 mins

If blocks ({#if}) in Svelte

Choose your learning style9 modes available
Introduction

If blocks let you show or hide parts of your webpage based on conditions. It helps make your page change when things happen.

Show a message only when a user is logged in.
Display a loading spinner while data is loading.
Hide a button after it is clicked.
Show different content based on user choices.
Syntax
Svelte
{#if condition}
  <!-- content to show if true -->
{:else if anotherCondition}
  <!-- content if anotherCondition is true -->
{:else}
  <!-- content if all conditions are false -->
{/if}
Use {#if} to start the block and {/if} to end it.
You can add {:else if} and {:else} parts to handle multiple cases.
Examples
Shows a welcome message only if loggedIn is true.
Svelte
{#if loggedIn}
  <p>Welcome back!</p>
{/if}
Shows a pass or fail message depending on the score.
Svelte
{#if score >= 50}
  <p>You passed!</p>
{:else}
  <p>Try again.</p>
{/if}
Handles three states: loading, error, and loaded.
Svelte
{#if status === 'loading'}
  <p>Loading...</p>
{:else if status === 'error'}
  <p>Error occurred.</p>
{:else}
  <p>Data loaded.</p>
{/if}
Sample Program

This Svelte component shows a button to log in or out. When clicked, it toggles the loggedIn state. The message below changes based on whether the user is logged in or not.

The button uses aria-pressed for accessibility to indicate its state.

Svelte
<script>
  let loggedIn = false;
  function toggleLogin() {
    loggedIn = !loggedIn;
  }
</script>

<button on:click={toggleLogin} aria-pressed={loggedIn}>
  {loggedIn ? 'Logout' : 'Login'}
</button>

{#if loggedIn}
  <p>Welcome back, user!</p>
{:else}
  <p>Please log in to continue.</p>
{/if}
OutputSuccess
Important Notes

Always close your if blocks with {/if}.

Use aria-pressed or similar attributes on interactive elements for better accessibility.

Test your conditions carefully to avoid showing wrong content.

Summary

If blocks let you show or hide content based on conditions.

Use {#if}, {:else if}, and {:else} to handle different cases.

They help make your app interactive and responsive to user actions.