Sub topic 6
Showing and hiding content with lwc:if
This chapter covers conditional rendering in Lightning Web Components. You decide in JavaScript whether a block of markup exists, and the template reacts to that decision. It assumes you can read modern JavaScript classes and getters, and that you know how {property} binding and reactive fields work from the earlier chapters.
The idea: conditions are computed, not written inline
A LWC template cannot evaluate an expression such as {items.length > 0}. The lwc:if directive accepts only a property reference, either a class field or a getter. The condition is computed in JavaScript, and the template reads the result.
This keeps the template declarative. It also makes the logic testable, because a getter is an ordinary class member you can read in a Jest test.
The three directives
Three directives work together as one chain:
| Directive | Role | Takes a value? |
|---|---|---|
| `lwc:if={condition}` | Starts the chain. Renders the element if the value is truthy. | Yes |
| `lwc:elseif={condition}` | Checked only if all earlier branches were falsy. | Yes |
| `lwc:else` | Renders if no earlier branch matched. | No |
The directives go on a <template> tag or on a regular HTML element. Using <template> is common because the wrapper tag itself is not added to the DOM. Only its children are rendered.
A first example
This cart component shows one message when there are items and another when the cart is empty.
<!-- cart.html -->
<template>
<template lwc:if={hasItems}>
<p>You have {itemCount} items in your cart.</p>
</template>
<template lwc:else>
<p>Your cart is empty.</p>
</template>
</template>// cart.js
import { LightningElement } from 'lwc';
export default class Cart extends LightningElement {
items = ['Pen', 'Notebook'];
get itemCount() {
return this.items.length;
}
get hasItems() {
return this.items.length > 0;
}
}The template never sees this.items. It reads itemCount and hasItems, and both are derived values. When items is reassigned, the getters run again on the next render and the correct branch appears.
What counts as truthy
lwc:if uses JavaScript truthiness. A getter does not have to return a strict boolean, but returning one makes the intent clear.
- Falsy values:
false,0,'',null,undefined,NaN. - Truthy values: everything else, including non-empty strings, non-zero numbers, objects, and empty arrays.
The empty array is the usual trap. lwc:if={items} is true even when items is [], so a getter that checks items.length > 0 is the correct tool.
// Wrong: [] is truthy, so the "has items" branch would render
get hasItemsWrong() {
return this.items;
}
// Right: an explicit boolean
get hasItems() {
return this.items.length > 0;
}If the field might be undefined before data arrives, guard it. This is common with data loaded from a server.
get hasItems() {
return Array.isArray(this.items) && this.items.length > 0;
}Chaining with lwc:elseif and lwc:else
Use lwc:elseif when you have more than two states. A typical case is a loading, error, and data trio.
<!-- accountPanel.html -->
<template>
<template lwc:if={isLoading}>
<p>Loading account...</p>
</template>
<template lwc:elseif={hasError}>
<p class="slds-text-color_error">{errorMessage}</p>
</template>
<template lwc:else>
<p>Account: {accountName}</p>
</template>
</template>// accountPanel.js
import { LightningElement } from 'lwc';
export default class AccountPanel extends LightningElement {
isLoading = true;
error;
accountName;
get hasError() {
return this.error !== undefined && this.error !== null;
}
get errorMessage() {
return this.hasError ? this.error.message || 'Unknown error' : '';
}
}Branches are evaluated in order, and the first truthy one wins. Put the most specific or most urgent state first. In the example, an error that arrives while isLoading is still true would be hidden. Make sure the code that handles a failed request sets isLoading = false.
Rules for the chain
- The branches must be adjacent siblings. Nothing but whitespace may sit between
lwc:ifand itslwc:elseiforlwc:else. lwc:elseifandlwc:elsecannot appear without a precedinglwc:if.lwc:elsetakes no value. Writinglwc:else={something}is a compile error.- The value must be a single
{property}reference. A negation such as{!hasItems}is not allowed. Add a getter likeisEmptyinstead.
get isEmpty() {
return !this.hasItems;
}Multiple conditions without nesting
When two independent conditions are involved, combine them in one getter rather than nesting templates.
get showEditButton() {
return this.isEditable && !this.isLocked && this.record !== undefined;
}<template lwc:if={showEditButton}>
<lightning-button label="Edit" onclick={handleEdit}></lightning-button>
</template>Nesting is still allowed when the inner condition only makes sense inside the outer one. Prefer a flat chain when you can. A named getter such as showEditButton also documents the business rule in one place.
What happens to the DOM
lwc:if adds and removes elements. It does not hide them with CSS. When the condition becomes false, the branch is removed from the DOM and any child components inside it are destroyed, which means their disconnectedCallback runs. When it becomes true again, new instances are created and connectedCallback runs again.
Two consequences follow:
- Local state inside a removed child is lost. If a user types into a form inside a branch that gets toggled off and on, the form comes back empty unless the parent keeps the data.
- Toggling expensive children has a cost. If a component is costly to create and the user flips the condition often, consider keeping it rendered and hiding it with a CSS class instead.
Toggling with a CSS class instead
If you want to keep the element and its state, bind a class that hides it. The next chapter on class binding covers this pattern in full, so a short version is enough here.
<!-- details.html -->
<template>
<lightning-button label={toggleLabel} onclick={handleToggle}></lightning-button>
<div class={panelClass}>
<c-heavy-chart></c-heavy-chart>
</div>
</template>// details.js
import { LightningElement } from 'lwc';
export default class Details extends LightningElement {
isOpen = false;
handleToggle() {
this.isOpen = !this.isOpen;
}
get toggleLabel() {
return this.isOpen ? 'Hide details' : 'Show details';
}
get panelClass() {
return this.isOpen ? '' : 'slds-hide';
}
}The chart is created once and stays in the DOM. The trade-off is that its work (data fetching, event listeners) continues while it is hidden.
| Approach | Element in DOM when hidden | Child state kept | Cost |
|---|---|---|---|
| `lwc:if` | No | No | Re-creation on each show |
| CSS class such as `slds-hide` | Yes | Yes | Hidden content still exists and may still run |
A complete interactive example
This component combines a reactive field, an event handler, getters, and a three-way chain. The user picks a status and the panel shows different content.
<!-- orderStatus.html -->
<template>
<lightning-combobox
label="Order status"
value={status}
options={statusOptions}
onchange={handleStatusChange}>
</lightning-combobox>
<template lwc:if={isShipped}>
<p>Your order is on its way.</p>
</template>
<template lwc:elseif={isDelivered}>
<p>Your order has arrived.</p>
</template>
<template lwc:else>
<p>Your order is being prepared.</p>
</template>
</template>// orderStatus.js
import { LightningElement } from 'lwc';
export default class OrderStatus extends LightningElement {
status = 'processing';
statusOptions = [
{ label: 'Processing', value: 'processing' },
{ label: 'Shipped', value: 'shipped' },
{ label: 'Delivered', value: 'delivered' }
];
handleStatusChange(event) {
this.status = event.detail.value;
}
get isShipped() {
return this.status === 'shipped';
}
get isDelivered() {
return this.status === 'delivered';
}
}Choosing "Shipped" reassigns status. That triggers a re-render, the getters run again, and the first branch becomes truthy. Note the event.detail.value here: lightning-combobox reports its value in detail, while the plain input in the earlier chapter used event.target.value.
Common errors
- Using an expression in the directive.
lwc:if={count > 0}andlwc:if={!isEmpty}fail to compile. Write a getter. - Passing a string.
lwc:if="hasItems"(no braces) is a compile error. Uselwc:if={hasItems}. - Placing content between branches. A stray
<p>betweenlwc:ifandlwc:elsebreaks the chain. - Treating an empty array as false. Check
.length. - Forgetting that state resets. A child inside a toggled branch is a new instance every time.
- Reading a nested property of something undefined. A getter like
this.account.namethrows ifaccounthas not loaded yet. Use optional chaining:this.account?.name.
Summary of the working model
- Compute the condition in a getter or hold it in a field.
- Reference it as a single
{property}inlwc:if,lwc:elseif, orlwc:else. - When a reactive field changes, the template re-renders and the chain is evaluated again from the top.
- The matching branch is added to the DOM, and the others are removed.
Exercise
A component has items = [] and the template contains <template lwc:if={items}>List goes here</template>. The list text still shows when the array is empty. Why, and how do you fix it? Also, why can't you write lwc:if={items.length} as the fix?
Show answer
An empty array is truthy in JavaScript, so lwc:if={items} renders the branch. The fix is a getter such as get hasItems() { return this.items.length > 0; } and lwc:if={hasItems}. The template accepts only a property reference, not a member access or expression, so items.length is not valid inside the braces of the directive. The computation belongs in the getter.
Exercise
A parent shows <c-note-editor> inside <template lwc:if={showEditor}>. A user types text, the parent sets showEditor to false and then back to true, and the text is gone. Give two ways to keep the text.
Show answer
The child is destroyed when the condition is false and recreated when it is true, so its internal state is lost. One option is to keep the text in the parent and pass it back to the child through an @api property. The other is to keep the child rendered and hide it with a CSS class such as slds-hide returned from a getter, so the instance is never removed.