Sub topic 10
Rendering conditionals and lists
This chapter assumes you know the earlier chapters on templates, data binding, and class-field reactivity. You should be able to read a bundle's HTML and JavaScript files and explain why reassigning a field re-renders the template.
LWC templates are declarative HTML. They have no if statement or for loop in the JavaScript sense. Instead, you put directives on <template> tags and elements, and the compiler turns them into rendering code. These directives are LWC additions. The browser does not know them. The compiler removes them before anything reaches the DOM.
Conditional rendering
A conditional directive decides whether an element and its children exist in the DOM. The current directives are lwc:if, lwc:elseif, and lwc:else. Each takes an expression that is a bare reference to a class member, such as {isLoading}.
<!-- statusPanel.html -->
<template>
<template lwc:if={isLoading}>
<p>Loading…</p>
</template>
<template lwc:elseif={hasError}>
<p class="error">Something went wrong: {errorMessage}</p>
</template>
<template lwc:else>
<p>Loaded {count} records.</p>
</template>
</template>// statusPanel.js
import { LightningElement } from 'lwc';
export default class StatusPanel extends LightningElement {
isLoading = false;
errorMessage = '';
count = 3;
get hasError() {
return this.errorMessage !== '';
}
}An inner <template> with a directive renders only its children. The <template> tag itself never appears in the DOM. You can also put the directive directly on a normal element such as <p lwc:if={isLoading}>. Use the <template> form when one condition guards several siblings, so you don't add a wrapper element.
Rules for the chain
lwc:elseifandlwc:elsemust be the next element sibling of thelwc:iforlwc:elseifbefore them. Putting other markup between them is a compile error.lwc:elsetakes no value.- When a branch is false, its elements are not created. Child components in that branch are not instantiated, so their
connectedCallbackdoes not run. When the branch becomes true, they are created. When it becomes false again, they are removed anddisconnectedCallbackruns.
The legacy directives
Older code uses if:true={value} and if:false={value}. They still work and you will see them in many existing components. They have no else-branch, so an if/else needs two separate directives. Those evaluate the same value twice and are easy to get out of sync. Prefer lwc:if in new code.
No expressions in templates
LWC templates do not allow {a && b}, {!isLoading}, or {items.length > 0}. The braces take a property path only. Any computed condition goes into a getter in the class, as hasError does above. This keeps the template simple and keeps logic where you can test it.
Rendering lists with for:each
To render an array, put for:each on a <template> element. Name the array, then use for:item to name the variable for the current element.
<!-- todoList.html -->
<template>
<ul>
<template for:each={items} for:item="item">
<li key={item.id}>{item.label}</li>
</template>
</ul>
</template>// todoList.js
import { LightningElement } from 'lwc';
export default class TodoList extends LightningElement {
items = [
{ id: 'a1', label: 'Write chapter' },
{ id: 'a2', label: 'Review chapter' }
];
addItem() {
const id = 'a' + (this.items.length + 1);
this.items = [...this.items, { id, label: 'New task ' + id }];
}
}addItem assigns a new array to this.items, and that reassignment triggers the re-render. Calling this.items.push(...) on a field holding a plain array does not reliably cause a re-render. Treat arrays and objects as immutable and replace them.
Keys
Every top-level element that the loop produces needs a key attribute, and the value must be a string or number that is unique among its siblings. The framework uses keys to match old and new list entries during a re-render. With stable keys it reuses existing DOM nodes and moves them. With unstable keys it destroys and recreates them, which discards state such as input focus and text typed into fields.
- Use an ID from your data, such as a record ID.
- Do not use the loop index. If an item is inserted at the top, every index shifts, so every element is matched to the wrong data.
- Do not generate keys during rendering, for example with a random number. A new key on every render means every element is recreated every time.
- The key goes on the first element inside the
for:eachtemplate, not on the<template>itself.
Index and iterator
for:each can also name the position with for:index, for example for:index="i". This is useful for display, such as numbering rows, but it should not become the key.
When you need to know whether an item is the first or last, use the iterator directive. It exposes value, index, first, and last.
<!-- tagList.html -->
<template>
<p>
<template iterator:it={tags}>
<span key={it.value.id}>
{it.value.name}<template lwc:if={it.last}>.</template>
<template lwc:if={it.first}> (first)</template>
</span>
</template>
</p>
</template>// tagList.js
import { LightningElement } from 'lwc';
export default class TagList extends LightningElement {
tags = [
{ id: 't1', name: 'web' },
{ id: 't2', name: 'lwc' },
{ id: 't3', name: 'standards' }
];
}The iterator name (it here) is yours to choose. You read the current element through it.value.
Combining conditionals and lists
A common need is to show a message when the list is empty. Because the template cannot test items.length, use a getter.
<!-- taskView.html -->
<template>
<template lwc:if={hasItems}>
<ul>
<template for:each={items} for:item="item">
<li key={item.id}>{item.label}</li>
</template>
</ul>
</template>
<template lwc:else>
<p>No tasks yet.</p>
</template>
</template>// taskView.js
import { LightningElement } from 'lwc';
export default class TaskView extends LightningElement {
items = [];
get hasItems() {
return this.items.length > 0;
}
}To filter a list, compute the filtered array in a getter and loop over the getter. Do not try to put a condition on the loop. If you do filter in a getter, return a new array each time and keep the original data in a field.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Compile error about a missing key | The element inside `for:each` has no `key` | Add `key={item.id}` to the first element in the loop |
| Compile error on `lwc:else` | Something sits between it and the preceding branch | Make the branches adjacent siblings |
| `{items.length > 0}` fails to compile | Expressions are not allowed in templates | Move the logic to a getter |
| List does not update after `push` | The field was mutated, not reassigned | Assign a new array |
| Input loses focus when the list changes | Keys are indexes or change every render | Use stable IDs from the data |
| Duplicate key warning | Two items share an ID | Make the IDs unique, or build a unique key in the data |
Standard or LWC addition?
None of these directives exist in browsers. The standard <template> element is inert, and nothing in the HTML specification loops over data or tests a condition. The LWC compiler reads for:each, iterator, and lwc:if. It then generates JavaScript that creates and updates ordinary DOM nodes. The result in the browser is plain elements inside a shadow root.
Exercise
A list component renders <li key={index}> using the loop index as the key. Users report that when a new item is added at the top of the list, text typed into an input inside an existing row appears in the wrong row. Why does this happen, and how do you fix it?
Show answer
Keys let the framework match existing DOM nodes to data items. With index keys, inserting at the top shifts every index. The node with key 0 (and the input value typed into it) is now matched to the new item, and every other node is matched to its neighbor's data. The fix is to give each data item a stable unique ID, such as a record ID, and use key={item.id}. Nodes then follow their data when the list changes.
Exercise
You want to show "No results" when results is an empty array. Why does <template lwc:if={results.length === 0}> fail, and what do you write instead?
Show answer
Template bindings accept only a property path, not expressions. Add a getter such as get isEmpty() { return this.results.length === 0; } to the class and write <template lwc:if={isEmpty}>.