Conditional Rendering in Svelte

The block {#if condition} ... {/if} shows markup only when the condition is true. Inside it there can be other branches (markup for other possibilities)…

Chicken Noodles is sold out, but its menu card still says "Available". The page needs to show different parts depending on the situation, and that's called conditional rendering. In Vue you use v-if, in React usually && or a ternary (the ? : operator) in JSX. Svelte has its own block in the markup: {#if}. A block is a piece of markup with an opening and a closing.

Picture the status boards in the display window at Mrs. Sri's stall. Mrs. Sri has three boards: "Available", "Only a few left" and "Sold out". Only one hangs at a time, depending on what's left in the pot. The other boards aren't covered with a cloth. They're kept in a drawer. In code, each board is one branch inside {#if}: the markup for one possibility. The chosen branch is on the page, like the board that hangs. The other branches aren't on the page at all, like the boards in the drawer.

{#if}: shown when the condition is true

In this example, the Sell 1 button lowers the stock of Chicken Noodles. The text Sold out shows only when the stock is 0:

<script>
  let stock = $state(2)
</script>

<button onclick={() => stock -= 1}>Sell 1</button>

{#if stock === 0}
  <p>Sold out</p>
{/if}
Event stock Shown below the button
Start 2 (nothing)
Click Sell 1 1 (nothing)
Click again 0 Sold out

{:else}: the other branch

This is the example from the first exercise:

<script>
  let loggedIn = $state(false)
</script>

{#if loggedIn}
  <p>Welcome!</p>
{:else}
  <p>Please log in</p>
{/if}

<button onclick={() => loggedIn = !loggedIn}>
  {loggedIn ? 'Logout' : 'Login'}
</button>
Event loggedIn <p> Button
Start false Please log in Login
Click true Welcome! Logout
Click again false Please log in Login

{:else if}: more than two possibilities

Mrs. Sri's status board has three possibilities. In code, each board becomes one branch (stock <= 3 means the stock is 3 or less):

{#if stock === 0}
  <p>Sold out</p>
{:else if stock <= 3}
  <p>Only {stock} left!</p>
{:else}
  <p>Available: {stock} portions</p>
{/if}
stock Shown
4 Available: 4 portions
2 Only 2 left!
0 Sold out

Svelte checks the conditions one by one, starting from the top branch, and stops at the first one that is true. The conditions below it aren't checked.

In the second exercise, you use the same pattern for a grade letter, with let score = 85 (>= means greater than or equal to):

{#if score >= 90}
  <p>A</p>
{:else if score >= 80}
  <p>B</p>
{:else if score >= 70}
  <p>C</p>
{:else}
  <p>D</p>
{/if}

A score of 95 becomes A, 85 becomes B, 75 becomes C, and 50 becomes D. With 85, the first condition (>= 90) is false and the second (>= 80) is true. So one <p> holding B shows. score never changes in this exercise, so a plain let is enough.

The order of branches decides

Now, in the status board code, the first two branches swap places, and there is no {:else}:

{#if stock <= 3}
  <p>Only {stock} left!</p>
{:else if stock === 0}
  <p>Sold out</p>
{/if}

Guess first: Chicken Noodles has 0 portions left. Does the page show Sold out or Only 0 left!?

It shows Only 0 left!. 0 <= 3 is true, and that condition comes first. So Svelte stops there and never reaches stock === 0. The code compiled by Svelte 5.16 shows the same thing (cut to the part that matters):

$.if(node, ($$render) => {
  if ($.get(stock) <= 3) $$render(consequent); else $$render(alternate, false);
});

When stock <= 3 is true, Svelte shows consequent (the first branch). When it is false, Svelte shows alternate (the rest of the branches), and stock === 0 is checked only inside that alternate.

The rule: put the narrowest condition first, meaning the condition that is true for the fewest values. stock === 0 is true only for 0, while stock <= 3 is true for 3, 2, 1 and also 0. So stock === 0 is narrower and goes first. For grade letters, score >= 90 must come before score >= 80. If score >= 70 were on top, a score of 85 would become C.

What isn't chosen isn't on the page

When the branch changes, Svelte removes the old branch's elements from the DOM, then creates the new branch's elements. When the branch stays the same, say from Only 3 left! to Only 2 left!, Svelte only replaces the number's text.

As a result, any text typed inside a branch disappears with it. Say there's an <input> (a text field) inside {#if open}, and you type "spicy". Then open becomes false, and then true again. The field is now empty, because it's a new field, not the one from before. If the text must stay, don't use {#if}. Hide the element with CSS, for example style="display: none".

Older code: Svelte 4

In Svelte 4 code, the blocks are exactly the same: {#if}, {:else if}, {:else}, {/if}. Only the way you write the state and the event differs. State is written let loggedIn = false without $state, because Svelte 4 tracked a plain let by itself. The click event is written on:click={() => loggedIn = !loggedIn}.

⚠️ An if block that won't compile, or a branch never chosen

TL;DR: The block {#if condition} ... {/if} shows markup only when the condition is true. Inside it there can be other branches (markup for other possibilities): {:else} for the opposite, and {:else if condition} for the next possibility. # opens the block, : continues to the next branch, / closes the block. Svelte checks from the top branch and stops at the first true condition. So put the narrowest condition (true for the fewest values) first. A branch that isn't chosen truly isn't in the DOM, and its content is created again when it's chosen again. A variable that a button changes is made with $state, and the button uses onclick. The exercises: let loggedIn = $state(false) shows Please log in and becomes Welcome! after a click; score = 85 with branches >= 90, >= 80, >= 70, {:else} shows B.

⚡ {#if} opens, {/if} closes

Write:

<script>
  let stock = $state(2)
</script>

<button onclick={() => stock -= 1}>Sell 1</button>

{#if stock === 0}
  <p>Sold out</p>
{/if}

Meaning: stock is the number of Chicken Noodles portions left, made with $state, and each click on Sell 1 lowers it. An {#if} block is markup with an opening and a closing. Its content only shows when the condition is true, so Sold out appears by itself once the stock reaches 0. The pattern: # opens the block, : continues to the next possibility, / closes the block. Every {#if} must be closed with {/if}. Without it, the compiler refuses with Block was left open.

⚡ {:else} for the opposite

Write:

{#if loggedIn}
  <p>Welcome!</p>
{:else}
  <p>Please log in</p>
{/if}

Meaning: loggedIn is true or false: logged in or not. {:else} opens a branch (markup for one possibility) that shows when the condition is false. So of these two branches, exactly one always shows. Every branch after the first uses a colon: {:else}, and {:else if} for another condition.

⚡ The order of branches decides

Write:

{#if stock <= 3}
  <p>Only {stock} left!</p>
{:else if stock === 0}
  <p>Sold out</p>
{/if}
Guess first: Chicken Noodles has 0 portions left. Does the page show Sold out or Only 0 left!?

Only 0 left!. 0 <= 3 is true and that condition comes first, so Svelte stops there.

Meaning: Svelte checks from the top branch and stops at the first true condition. Put the narrowest condition (true for the fewest values) first: stock === 0 goes on top.

What you will learn