Sub topic 15
Common mistakes and how to avoid them
This chapter assumes you can write a Lightning Web Component with an HTML template and a JavaScript class. It also assumes you know how to bind properties with curly braces and how reactive fields and event handlers work. It collects the errors that come up most often with lwc:if, lwc:elseif, and lwc:else, and shows how to fix each one.
Putting an expression in the condition
The value of lwc:if and lwc:elseif must be a plain property or getter reference. Templates do not evaluate JavaScript expressions. Negation, comparison, and method calls all fail to compile.
<template>
<!-- Does not compile -->
<template lwc:if={!isLoading}>
<p>Ready</p>
</template>
<template lwc:if={status === 'error'}>
<p>Error</p>
</template>
</template>Move the logic into getters and give each getter a name that describes the condition.
import { LightningElement } from 'lwc';
export default class StatusPanel extends LightningElement {
status = 'loading';
get isReady() {
return this.status !== 'loading';
}
get hasError() {
return this.status === 'error';
}
}<template>
<template lwc:if={hasError}>
<p>Error</p>
</template>
<template lwc:elseif={isReady}>
<p>Ready</p>
</template>
</template>A negated getter such as isNotLoading is acceptable. For a simple two-way choice, lwc:if followed by lwc:else often removes the need for a negated getter entirely.
Breaking the chain
lwc:elseif and lwc:else belong to the lwc:if block directly before them. The compiler needs them to be adjacent siblings. Another element between the branches ends the chain, and the compiler reports an error.
<template>
<template lwc:if={isLoading}>
<p>Loading...</p>
</template>
<hr>
<template lwc:else>
<p>Done</p>
</template>
</template>The <hr> separates the two blocks, so lwc:else has nothing to attach to. Move the shared element inside each branch, or place it before or after the whole chain.
Other chain errors follow the same pattern:
- Starting a chain with
lwc:elseiforlwc:else. A chain always begins withlwc:if. - Writing
lwc:else={something}. Thelwc:elsedirective takes no value, so write it bare. - Putting two directives from the same chain on one element, such as
lwc:elseandlwc:elseiftogether. - Putting a new
lwc:elseifafter anlwc:else. Thelwc:elsebranch ends the chain.
Expect an else branch with a value to be rejected. Write <template lwc:else>, not <template lwc:else={fallback}>.
Misreading truthy and falsy values
The condition is judged by JavaScript truthiness. Three cases surprise people.
| Value | Truthy? | Effect |
|---|---|---|
| `0` | No | A count of zero hides the branch. |
| `[]` (empty array) | Yes | `lwc:if={items}` still renders for an empty list. |
| `'false'` (string) | Yes | Any non-empty string renders the branch. |
The empty array is the most frequent trap. Binding the array directly tells you only that it exists. Use a getter that states what you mean.
import { LightningElement } from 'lwc';
export default class OrderList extends LightningElement {
orders = [];
get hasOrders() {
return this.orders.length > 0;
}
handleAdd() {
this.orders = [...this.orders, { id: this.orders.length + 1 }];
}
}<template>
<template lwc:if={hasOrders}>
<p>You have orders.</p>
</template>
<template lwc:else>
<p>No orders yet.</p>
</template>
<button onclick={handleAdd}>Add order</button>
</template>The same code also avoids a second problem. handleAdd assigns a new array instead of calling push. A field is reactive when you reassign it. Changes made inside an array or object do not trigger a re-render unless the field is decorated with @track. If lwc:if does not react to your change, check whether you mutated a value in place.
Mixing legacy and current directives
if:true and if:false are the older directives. They still work, but they cannot form a chain. if:false={isVisible} is not an else. It is a second, independent test of the same property. Mixing the two styles in one template makes the logic hard to follow, and putting lwc:if and if:true on the same element is rejected by the compiler.
<template>
<!-- Legacy: two independent tests -->
<template if:true={isVisible}>
<p>Visible</p>
</template>
<template if:false={isVisible}>
<p>Hidden</p>
</template>
<!-- Current: one linked block -->
<template lwc:if={isVisible}>
<p>Visible</p>
</template>
<template lwc:else>
<p>Hidden</p>
</template>
</template>When you migrate, convert a whole related group at once. Replace if:true with lwc:if and an if:false that repeats the same property with lwc:else. If an if:false tested a different property, it is not an else, so give it its own lwc:if with a getter.
Querying for elements that are not rendered yet
A branch that is not rendered has no DOM. Code that looks for an element inside a conditional block can get null.
import { LightningElement } from 'lwc';
export default class SearchBox extends LightningElement {
showInput = false;
handleShow() {
this.showInput = true;
// Wrong: the input does not exist until the re-render finishes.
const input = this.template.querySelector('input');
input.focus(); // TypeError: input is null
}
}The re-render happens after the handler finishes. Run DOM-dependent code in renderedCallback, and guard it so it runs only once.
import { LightningElement } from 'lwc';
export default class SearchBox extends LightningElement {
showInput = false;
needsFocus = false;
handleShow() {
this.showInput = true;
this.needsFocus = true;
}
renderedCallback() {
if (this.needsFocus) {
const input = this.template.querySelector('input');
if (input) {
input.focus();
this.needsFocus = false;
}
}
}
}<template>
<button onclick={handleShow}>Search</button>
<input lwc:if={showInput} type="text" aria-label="Search">
</template>Forgetting that toggling destroys state
When a branch becomes false, LWC removes its elements. Child components inside it are disconnected, and disconnectedCallback runs. When the branch becomes true again, LWC creates new instances, so constructor and connectedCallback run again. Any state held in the old child, such as typed text or a scroll position, is gone.
Two mistakes follow from this:
- Expecting a child to keep its state across toggles. Store that state in the parent and pass it down, or hide the child with CSS instead.
- Placing expensive work such as server calls in
connectedCallbackof a child that toggles often. The work repeats on every toggle.
Choose between the two approaches by what you need to keep.
| Need | Use |
|---|---|
| Free resources, keep the DOM small | `lwc:if` |
| Keep child state and avoid repeated setup | CSS hiding, such as the `slds-hide` class |
| Content that is rarely shown and costly to build | `lwc:if` |
Hiding with CSS is not a security measure. The hidden content is still in the DOM, so never use it to conceal data a user should not see.
Putting heavy work in getters
LWC may evaluate a getter every time the template re-renders. Keep conditional getters cheap and free of side effects. Do not fetch data, change fields, or sort large arrays inside them. Compute the result in an event handler or lifecycle hook, store it in a field, and let the getter read that field.
A quick debugging path
When a branch does not show the way you expect, work through these checks in order.
Exercise
A template contains <template lwc:if={items}> where items is an array loaded from a server call. The list shows "You have items" even when the server returned no records. Why does this happen, and how do you fix it?
Show answer
An empty array is truthy in JavaScript, so lwc:if={items} renders whenever the array exists. Add a getter such as get hasItems() { return this.items.length > 0; } and bind lwc:if={hasItems}. Pair it with lwc:else for the empty-state message.
Exercise
A child form component sits inside <template lwc:if={showForm}>. Users complain that text they typed disappears when they toggle showForm off and on. Explain the cause and give one fix.
Show answer
Setting showForm to false removes the child and destroys its instance. Setting it to true creates a new instance with empty state. One fix is to keep the form in the DOM and hide it with a CSS class such as slds-hide. Another is to store the typed values in the parent and pass them down as properties.