Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 35 ยท Templates and Markup

Conditional Rendering with {#if}

Show and hide markup in Svelte 5 with {#if}, {:else if} and {:else}, plus {#key}, {#await} for promises and patterns for loading and empty states.

Apps constantly decide what to show: a login form or a profile, a spinner or a result, an empty message or a list. Svelte handles this with blocks, written with {#...} to open, {:...} to continue and {/...} to close. This lesson covers {#if}, {#key} and {#await}.

if, else if, else

SVELTE
<script>
  let temperature = $state(21);
</script>

<input type="range" min="-10" max="40" bind:value={temperature} />

{#if temperature < 0}
  <p>Freezing: {temperature} C</p>
{:else if temperature < 18}
  <p>Cool: {temperature} C</p>
{:else}
  <p>Warm: {temperature} C</p>
{/if}

The condition can be any JavaScript expression. Svelte re-evaluates it whenever the state it reads changes, and creates or destroys the DOM nodes of the branch that comes and goes. A branch that is not shown does not exist in the DOM at all, unlike display: none.

How {#if} updates

Condition Reads state
Branch changes Old nodes removed
New nodes Created and inserted

Nothing to patch inside a branch that did not change.

1 / 2

Truthy and falsy

{#if user} runs when user is truthy. Remember that 0, '', null, undefined, NaN and false are falsy, so {#if count} hides when count is zero. When zero is meaningful, be explicit: {#if count !== undefined}.

Nested conditions and early returns

Svelte markup has no return, so a common style is to put the failure and empty cases first:

SVELTE
{#if error}
  <p class="error">{error.message}</p>
{:else if !items}
  <p>Loading...</p>
{:else if items.length === 0}
  <p>No results.</p>
{:else}
  <ul>
    {#each items as item}<li>{item}</li>{/each}
  </ul>
{/if}

Each state of your data gets its own readable branch. Spelling out loading, error, empty and success states is a habit that improves real apps a lot.

Hiding without removing

If you want to keep the node and its state but hide it visually (for example to preserve a video's playback), toggle a class or the hidden attribute instead:

SVELTE
<div hidden={!open}>Details...</div>
<div class:visually-hidden={!open}>Details...</div>

{#key}: recreate on change

{#key expression} destroys and recreates its content whenever the expression changes. It is the tool for restarting an animation or resetting a component's internal state:

SVELTE
{#key page}
  <article>Page {page}</article>
{/key}

{#await}: promises in the template

{#await} renders different markup for the pending, fulfilled and rejected stages of a promise:

SVELTE
<script>
  async function loadUser(id) {
    const response = await fetch(`/api/users/${id}`);
    if (!response.ok) throw new Error('Not found');
    return response.json();
  }

  let id = $state(1);
  let promise = $derived(loadUser(id));
</script>

{#await promise}
  <p>Loading...</p>
{:then user}
  <p>{user.name}</p>
{:catch error}
  <p class="error">{error.message}</p>
{/await}

Shorthands exist: {#await promise then value}...{/await} skips the pending branch. In SvelteKit, prefer fetching data in a load function so the server can do the work before the page is sent.

Stand-in: branch switching

This stand-in picks a branch from a list of [condition, template] pairs, which mirrors the if / else if / else chain, and prints which branch is active.

JS Branch chain (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Order matters: the error branch comes first, so it wins even when items is present.

Pending, then, catch (stand-in page)

Common mistakes

  • Using {#if count} when zero should still render.
  • Forgetting that hidden branches lose their internal state; use hidden or CSS when you must keep it.
  • Doing heavy fetching in the template instead of a load function in SvelteKit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between {#if} and display: none?

    A false {#if} branch is not in the DOM at all.
  2. 2. What does {#key page} do when page changes?

    {#key} is used to restart animations or reset component state.
  3. 3. Which branch of {#await} shows while the promise is pending?

    The markup right after {#await promise} is the pending state.
  4. 4. Why use explicit checks like count !== undefined in {#if}?

    Truthiness hides 0 and empty strings, which are often valid values.

Summary

  • {#if}, {:else if}, {:else} create and destroy branches in the DOM.
  • Spell out loading, error, empty and success states in order.
  • Use hidden or CSS to hide without losing internal state.
  • {#key} recreates content on change; {#await} renders promise stages.

Next: Lists with {#each}