Skip to content

Svelte Conditional Rendering — Logic Blocks Deep Dive

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Svelte Conditional Rendering. We cover key concepts, practical examples, and best practices to help you master this topic.

Svelte's {#if} block conditionally renders content based on JavaScript expressions, supporting {:else if} and {:else} branches for complex conditional layouts.

What You'll Learn

  • {#if} and {:else} blocks
  • {:else if} chains
  • Nested conditionals
  • Combining with reactive declarations
  • Conditional class and styles

Why It Matters

Conditional rendering controls what users see based on application state. Svelte's logic blocks are compiled to direct DOM manipulation with no diffing overhead.

<script>
  let status = "loading";
  let error = null;
  let data = null;

  async function fetchData() {
    status = "loading";
    try {
      const res = await fetch("/api/data");
      if (!res.ok) throw new Error("Failed to fetch");
      data = await res.json();
      status = "success";
    } catch (e) {
      error = e.message;
      status = "error";
    }
  }
</script>

<button on:click={fetchData}>Load Data</button>

{#if status === "loading"}
  <div class="spinner">Loading...</div>
{:else if status === "error"}
  <div class="error">Error: {error}</div>
  <button on:click={fetchData}>Retry</button>
{:else if status === "success"}
  <div class="success">
    <h3>Data Loaded</h3>
    {#if data.items.length > 0}
      <ul>
        {#each data.items as item}
          <li>{item.name}</li>
        {/each}
      </ul>
    {:else}
      <p>No items found</p>
    {/if}
  </div>
{/if}

Expected output: Initial loading state, error state with retry on failure, and success state with list or empty message.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro