Sub topic 8
Adding branches with lwc:elseif
This chapter assumes you can write a Lightning Web Component with an HTML template and a JavaScript class, bind properties with curly braces, and write getters. It also assumes you have used lwc:if to show or hide a block. Here you add middle branches to a conditional block.
Why a single lwc:if is not enough
A lone lwc:if handles two outcomes: the content shows or it doesn't. Many interfaces have three or more mutually exclusive states. A data panel can be loading, failed, empty, or showing records. A badge can be gold, silver, or bronze.
You could write several independent lwc:if blocks, each with its own condition. This works, but every condition must exclude all the others by hand. If one condition is wrong, two blocks can render together, or none can.
lwc:elseif links a new condition to the block before it. The engine tests the conditions in order and renders only the first branch that matches.
The basic shape
An lwc:elseif takes a condition in curly braces, just like lwc:if. The condition must be a simple property reference, such as {hasError}. It can't be an expression like {status === 'error'}. You can put it on a <template> tag or directly on an element.
<template>
<template lwc:if={isLoading}>
<p>Loading...</p>
</template>
<template lwc:elseif={hasError}>
<p>Something went wrong.</p>
<button onclick={handleRetry}>Retry</button>
</template>
<template lwc:else>
<p>Data is ready.</p>
</template>
</template>The engine evaluates the chain from top to bottom:
- If
isLoadingis truthy, it renders the first block and skips the rest. - Otherwise, if
hasErroris truthy, it renders the second block. - Otherwise, it renders the
lwc:elseblock.
The lwc:else branch is optional. Without it, the chain renders nothing when every condition is falsy.
Conditions come from getters
Because the template accepts only property references, you move comparisons into getters. The class below stores one status string and exposes a getter for each branch.
import { LightningElement } from 'lwc';
export default class StatusPanel extends LightningElement {
status = 'loading';
get isLoading() {
return this.status === 'loading';
}
get hasError() {
return this.status === 'error';
}
handleRetry() {
this.status = 'loading';
}
}When handleRetry sets status back to 'loading', the component re-renders. The engine re-evaluates the chain, finds isLoading truthy, and swaps the error block for the loading block. The template needs no extra code to make this happen.
Storing one status value instead of several booleans has a practical benefit. A single string can only hold one value, so the component can't be in two states at once. With separate isLoading and hasError fields, a bug could set both to true. The chain would still render only the first match, but your logic would be inconsistent.
Using more than one lwc:elseif
You can place any number of lwc:elseif branches between the lwc:if and the optional lwc:else. Order matters, because the first truthy condition wins.
<template>
<template lwc:if={isGold}>
<p>Gold member</p>
</template>
<template lwc:elseif={isSilver}>
<p>Silver member</p>
</template>
<template lwc:elseif={isBronze}>
<p>Bronze member</p>
</template>
<template lwc:else>
<p>Standard member</p>
</template>
</template>import { LightningElement, api } from 'lwc';
export default class MemberBadge extends LightningElement {
@api points = 0;
get isGold() {
return this.points >= 1000;
}
get isSilver() {
return this.points >= 500;
}
get isBronze() {
return this.points >= 100;
}
}Here the conditions overlap. A member with 1200 points satisfies all three getters. Only the gold block renders, because the chain stops at the first match. This lets you write simple thresholds without adding an upper bound to each getter. If you reorder the branches so isBronze comes first, every member with 100 or more points would show as bronze. Put the most specific or highest-priority condition first.
Placing directives on elements
When only one element is conditional, you can skip the wrapping <template> and put the directive on the element itself. The same works for lwc:elseif.
<template>
<p lwc:if={isEmpty}>Your list is empty.</p>
<p lwc:elseif={hasOneItem}>You have one item.</p>
<p lwc:else>You have {itemCount} items.</p>
</template>Use a <template> tag when a branch holds several sibling elements. Use the element form when the branch is a single element. Both render the same way. The <template> tag itself never appears in the DOM; only its children do.
Rules for a valid chain
A chain is a set of linked sibling nodes. The compiler checks several rules and reports an error if you break them.
| Rule | Valid | Invalid |
|---|---|---|
| A chain starts with `lwc:if`. | `lwc:if` then `lwc:elseif` | `lwc:elseif` with no `lwc:if` before it |
| Branches are adjacent siblings. | Branches follow one another directly | Another element sits between two branches |
| `lwc:elseif` needs a condition. | `lwc:elseif={hasError}` | `lwc:elseif` with no value |
| `lwc:else` takes no value. | `lwc:else` | `lwc:else={something}` |
| `lwc:else` comes last. | `lwc:else` ends the chain | `lwc:elseif` after `lwc:else` |
The adjacency rule causes the most surprises. Consider this template:
<template>
<template lwc:if={isLoading}>
<p>Loading...</p>
</template>
<hr>
<template lwc:elseif={hasError}>
<p>Error</p>
</template>
</template>The <hr> breaks the chain, so the lwc:elseif has no lwc:if to attach to, and compilation fails. Move the <hr> inside a branch or place it before or after the whole chain.
Truthiness decides each branch
Each condition is evaluated as a JavaScript truthy or falsy value. The values false, 0, '', null, undefined, and NaN are falsy. Everything else is truthy, including the string 'false' and an empty array.
This matters in chains because a falsy-looking value can fall through to a later branch:
<template>
<template lwc:if={records}>
<p>Showing records.</p>
</template>
<template lwc:elseif={error}>
<p>Failed to load.</p>
</template>
<template lwc:else>
<p>Loading...</p>
</template>
</template>If records is an empty array, it is truthy, so the first branch renders even though there is nothing to show. If you want a separate empty state, use a getter that checks the length:
get hasRecords() {
return Array.isArray(this.records) && this.records.length > 0;
}Nesting inside a branch
A branch can contain its own chain. The inner chain is independent of the outer one, so its lwc:else pairs only with its own lwc:if.
<template>
<template lwc:if={isReady}>
<template lwc:if={hasRecords}>
<p>Showing {recordCount} records.</p>
</template>
<template lwc:else>
<p>No records found.</p>
</template>
</template>
<template lwc:elseif={hasError}>
<p>Something went wrong.</p>
</template>
<template lwc:else>
<p>Loading...</p>
</template>
</template>Keep nesting shallow. If you nest more than two levels, consider moving the inner block into a child component or computing a single status value in JavaScript.
What happens when a branch changes
When the active branch changes, the engine removes the old branch's DOM and creates the new one. Any child components inside the old branch are disconnected, and their disconnectedCallback runs. Child components in the new branch are created fresh, and their constructor and connectedCallback run.
This has a consequence for state. A child component that was in a removed branch loses its internal state. If the user returns to that branch, they get a new instance that starts from its defaults. Keep state you want to preserve in the parent, and pass it down with @api properties.
Branches that stay the same are not recreated. If status changes from 'loading' to 'loading', nothing happens.
Common mistakes
- Writing an expression in the braces.
lwc:elseif={status === 'error'}doesn't compile. Use a getter. - Separating branches with other markup. Any node between two branches breaks the chain.
- Giving
lwc:elsea value. It is written as a bare attribute. - Ordering overlapping conditions wrongly. The first truthy branch wins, so put the most specific condition first.
- Treating an empty array as falsy. Check
lengthin a getter. - Expecting state to persist. Switching branches destroys child components in the old branch.
Exercise
A template has lwc:if={isAdmin}, then an lwc:elseif={isEditor}, then an lwc:else. A user is both an admin and an editor, so both getters return true. Which branch renders, and why? Then name one change that would break the chain at compile time.
Show answer
Only the isAdmin branch renders. The engine evaluates branches in order and stops at the first truthy condition, so isEditor is never checked. The chain breaks at compile time if you place another element between the lwc:if and lwc:elseif blocks, if you write lwc:else={value} with a value, or if you put an lwc:elseif after the lwc:else.
Exercise
A component stores items = [] and uses lwc:if={items} followed by lwc:else that shows "No items". The "No items" message never appears. Why, and how do you fix it?
Show answer
An empty array is truthy in JavaScript, so lwc:if={items} always matches and the lwc:else branch never runs. Add a getter such as get hasItems() { return this.items.length > 0; } and bind lwc:if={hasItems} instead.