Svelte 21 š§” Conditional Rendering Control Flow Blocks ({#if}, {:else if}, {:else})
Svelte 5 continues the tradition of highly declarative UI logic by providing built-in control flow blocks. Conditional renderingāthe ability to show or hide parts of the DOM based on reactive stateāis fundamental to modern application development. By using syntax that lives directly within the markup, Svelte ensures that your UI logic remains tightly coupled to your data without requiring complex nested ternary operators or auxiliary function calls in JavaScript.
The control flow blocks in Svelte 5 are designed to be efficient and readable. When the reactive signal driving an {#if} block changes, Svelte updates the DOM in the most performant way possible, adding or removing elements only when necessary. This chapter walks through the syntax and usage patterns of the conditional block, explaining how to handle multiple branches and why this approach is preferred over standard JavaScript expression-based rendering.
Key point: Svelte conditional blocks are declarative structures that manage DOM creation and removal based on reactive state, ensuring the UI always reflects the current data while maintaining optimal performance.
Why Conditional Rendering Blocks exist
The complexity of nested ternaries. While JavaScript supports ternary operators, nesting them in templates leads to “spaghetti code” that is difficult to parse and debug. Block syntax provides a clear, structural visual guide.
The performance of targeted reconciliation. Unlike array-based map approaches in other frameworks, Svelte blocks are “first-class” citizens. The compiler understands exactly which DOM nodes belong to which block, allowing for granular updates rather than full-component re-renders.
The readability of structural intent. Seeing {#if} and {:else} allows a developer to immediately understand the layout logic of a component without interpreting functional logic or conditional style classes.
The scope safety. Control blocks create lexical scopes for their content. This allows Svelte to perform static analysis and ensure that variables are only accessed when the corresponding DOM nodes actually exist, preventing null pointer exceptions.
The declarative standard. By keeping logic inside the template, Svelte maintains a clear separation between side-effect-prone imperative code in script blocks and the descriptive layout of the UI.
a. The base {#if} block structure
The {#if} block is the foundation of conditional logic in Svelte. It checks a reactive variable (a signal) and mounts the children to the DOM only when the condition evaluates to true. When the condition becomes false, the DOM is pruned.
{#if isLoggedIn}
<button>Log Out</button>
{/if}
The logic inside the block is reactive. If isLoggedIn is toggled in your script, Svelte automatically updates the UI. Because the block is managed by the Svelte compiler, it is aware of the component’s reactive dependency graph, meaning it will only re-evaluate when isLoggedIn specifically changes.
b. Chaining with {:else if} and {:else}
To handle complex logic involving multiple states, Svelte provides {:else if} and {:else} blocks. These allow you to sequence conditions gracefully without flattening the DOM with multiple independent if checks.
{#if role === 'admin'}
<AdminPanel />
{:else if role === 'moderator'}
<ModPanel />
{:else}
<UserPanel />
{/if}
This structure is strictly evaluated from top to bottom. Once one condition is met, the remaining blocks are ignored. This efficiency ensures that even if you have a massive state object, the browser only ever has to manage the DOM nodes for the active branch of your conditional tree.
c. Scope and reactivity integration
One of the strengths of Svelteās conditional blocks is their tight integration with state. Because these blocks are managed by the reactive system, you can use them to safely render data that might only exist under specific conditions, effectively acting as an optional guard for your application logic.
{#if user?.profile}
<img src={user.profile.avatarUrl} alt="Avatar" />
{/if}
In the example above, the block acts as a null guard. Svelteās reactivity system ensures that the user.profile object is only accessed if the condition is true. This prevents runtime errors that might occur if you tried to access a property on an undefined object before the data had finished loading from an API.
Complete Example Session
// ============================================
// PART 1: DEFINING STATE
// ============================================
let status = $state('loading'); // 'loading' | 'success' | 'error'
// ============================================
// PART 2: CONDITIONAL RENDERING
// ============================================
{#if status === 'loading'}
<p>Please wait...</p>
{:else if status === 'success'}
<button>Continue</button>
{:else}
<p>Something went wrong.</p>
<button onclick={() => status = 'loading'}>Retry</button>
{/if}
// ============================================
// PART 3: DYNAMIC UPDATES
// ============================================
function loadData() {
status = 'loading';
// simulated fetch...
status = 'success';
}
This sequence covers the base if block, the chaining of else if and else, and the reactive update mechanism that toggles the UI visibility based on the internal state.
Quick Reference
Control Block Syntax
| Block | Purpose |
|---|---|
{#if cond} | Starts the block |
{:else if cond} | Adds a middle condition |
{:else} | The fallback branch |
{/if} | Closes the block |
Behavior Matrix
| Feature | Svelte Block | JS Ternary |
|---|---|---|
| Readability | High | Low |
| DOM Reconciliation | Granular | Full update |
| Scope Safety | Excellent | Poor |
| Multi-branching | Easy | Complex |
Best Practices
ā Do This:
{#if items.length > 0}
<List {items} />
{:else}
<EmptyState />
{/if} // ā
{#if user.isAdmin} <AdminControls /> {/if} // ā
ā Don’t Do This:
{items.length > 0 ? <List items={items}/> : <EmptyState/>} // ā
{#if a} <div></div> {/if}
{#if !a} <span></span> {/if} // ā
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Missing closer | Forgetting {/if} | Ensure tags are paired |
| Logic leakage | Using complex expressions | Use $derived for logic |
| Performance | Too many nested blocks | Simplify component structure |
| State mismatch | Wrong conditional var | Audit reactive signal |
Real-World Examples
1. Auth gate
{#if user} <Dashboard /> {:else} <Login /> {/if}
2. Loading spinner
{#if loading} <Spinner /> {/if}
3. Role-based view
{#if role === 'admin'} <Admin /> {:else if role === 'user'} <Guest /> {/if}
4. Error handling
{#if error} <ErrorMsg msg={error} /> {/if}
5. Null guard
{#if data} {data.val} {/if}
6. Toggle switch
{#if visible} <div>Content</div> {/if}
7. Mobile vs Desktop
{#if isMobile} <MobileMenu /> {:else} <Nav /> {/if}
8. Validation feedback
{#if touched && !valid} <p>Invalid</p> {/if}
9. Theme switcher
{#if theme === 'dark'} <DarkIcon /> {:else} <LightIcon /> {/if}
10. Empty collection
{#if list.length === 0} <p>No items</p> {/if}
Visual
Conditional Branching Structure
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā CONDITION CHECK (Signal) ā
ā ā ā
ā āāā TRUE āāāŗ Render Block A ā
ā ā ā
ā āāā FALSE āāāŗ Check Block B ā
ā ā ā
ā āāā TRUE āāāŗ Render Bā
ā ā ā
ā āāā FALSE āāāŗ Render Cā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
DOM Reconciliation
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā STATE: False āāāŗ True ā
ā ā
ā DOM: ā
ā [Hidden] āāāŗ [Mount Element] ā
ā [Cleanup] āāā [State: False] ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
Scoping Illustration
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā {#if user} ā
ā // user scope exists here ā
ā {/if} ā
ā // user scope undefined here ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
Summary
| Item | Value |
|---|---|
| Block Start | {#if} |
| Middle | {:else if} |
| Fallback | {:else} |
| Block End | {/if} |
| Reactivity | Automatic |
Key takeaways:
- Prefer control flow blocks. They are more readable, performant, and safer than ternary operators inside templates.
- Granular updates. Svelte tracks dependencies precisely, so the DOM only updates when the condition result changes.
- Use for null protection. Conditional blocks naturally guard against accessing properties on undefined or null objects.
- Chain logically. Use
{:else if}for sequences to keep your code clean and prevent overly deep nesting. - Maintain scope. Variable access inside the block is protected, making it easy to reason about data existence.
Remember: Conditional rendering blocks are the backbone of dynamic Svelte interfaces. They turn your application data into visual reality by providing a clean, structural way to dictate what the user sees based on their interaction with the app. By using them consistently, you ensure your template remains descriptive, high-performing, and easy to maintain as your application grows in complexity.
Stop using slow, ad-bloated tool sites! š¤®
š Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
ā
Finance (Mortgage, Interest, Inflation)
ā
Tech (Base64, JSON, Dev Suite, IP)
ā
Health (BMI, BMR, TDEE)
ā
Productivity (Timer, Workspace, QR)
ā”ļø Fast & Private
š No data leaves your device
š 100% Free
š Use it now: https://tools.kandz.me
š Bookmark itāyouāll need it later!