Sub topic 8
Rendering lists with for:each and key
This chapter assumes you can read basic HTML and modern JavaScript (classes, arrow functions, template literals). It also assumes you have created a Lightning Web Component bundle and know that a class field can be bound with { }. You also need to know that a template accepts only a property or getter reference, not an expression. Here you will turn an array into repeated markup, and you will learn why the key attribute is required and where it goes.
The shape of a list in LWC
A template cannot run a loop in JavaScript syntax. It has directives that repeat a block of markup once per array item. The two directives are for:each and iterator. Both take a property or getter that returns an array.
The data flow has three steps:
- The class holds raw data, such as an array of contact records.
- A getter reshapes that data into what the template needs, for example a
labelstring and a uniqueid. - The template loops over the getter's result and binds each item's simple properties.
A basic list
This getter prepares the list items. It adds a computed label, because the template cannot evaluate {contact.firstName} {contact.lastName} as one expression.
// contactList.js
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
contacts = [
{ id: '1', firstName: 'Ada', lastName: 'Lovelace' },
{ id: '2', firstName: 'Alan', lastName: 'Turing' }
];
get displayContacts() {
return this.contacts.map((c) => ({
id: c.id,
label: `${c.firstName} ${c.lastName}`
}));
}
}The template iterates over the getter's result:
<!-- contactList.html -->
<template>
<ul>
<template for:each={displayContacts} for:item="contact">
<li key={contact.id}>{contact.label}</li>
</template>
</ul>
</template>
</parameter>Each part has a job:
for:each={displayContacts}names the array. It is a bare property reference, like any other binding.for:item="contact"names the variable that holds the current item. The value is a quoted string, not a binding. Inside the loop, you reach the item with{contact.label}.- The
<template>element that carries the directives renders nothing itself. Only its children appear in the DOM. key={contact.id}gives each rendered item a stable identity.
The rendered output is two li elements, "Ada Lovelace" and "Alan Turing".
Rules for key
The key attribute is the most common source of list errors in LWC. These rules cover nearly all of them.
| Rule | Why it matters |
|---|---|
| Put `key` on the first element inside the loop template. | The compiler looks for it there. Putting it on the wrapping `<template>` tag or on a deeper child fails. |
| The value must be a string or a number. | Objects and booleans are not valid keys. |
| The value must be unique among siblings in that list. | Duplicate keys make the engine reuse the wrong element. |
| The value must be stable for the same data record. | A key that changes on every render forces the engine to destroy and recreate elements. |
| Do not use the array index as the key. | When items are inserted, removed, or reordered, an index points to different data than before. |
What the key does
When the array changes and the component re-renders, the engine compares the old and new lists. Keys tell it which new item corresponds to which old element. With stable keys, it moves, adds, or removes only the elements that actually changed. It also keeps internal state, such as the text a user typed into an input in row 3, attached to the right row.
With index keys, the engine thinks that "row 0" is always the same element. If you remove the first record, every row after it appears to change its data, and typed input stays in its old position while the data shifts under it.
A bug caused by an index key
Suppose each row has an input. With key={contact.index}, a user types a note into the first row, and then your code removes the first contact. The note stays in the first row, but it now sits next to the second contact's name. Keying by contact.id avoids this, because the engine removes the element with that id and leaves the rest alone.
Showing the position with for:index
If you need the position for display, add for:index. The value is a zero-based number.
<!-- rankedList.html -->
<template>
<ol>
<template for:each={displayContacts} for:item="contact" for:index="position">
<li key={contact.id}>
Position {position}: {contact.label}
</li>
</template>
</ol>
</template>Note that {position} is zero-based. If you want to display "1" for the first row, compute a displayNumber in the getter instead, because the template cannot add 1 inline:
// rankedList.js
import { LightningElement } from 'lwc';
export default class RankedList extends LightningElement {
contacts = [
{ id: 'a', name: 'Ada' },
{ id: 'b', name: 'Alan' }
];
get displayContacts() {
return this.contacts.map((c, index) => ({
id: c.id,
label: `${index + 1}. ${c.name}`
}));
}
}Using iterator for first and last
The iterator directive is an alternative to for:each. It exposes the current item and two flags, first and last. These are useful for adding separators or special markup at the edges of a list.
<!-- breadcrumbs.html -->
<template>
<nav>
<template iterator:it={crumbs}>
<span key={it.value.id}>
<template lwc:if={it.first}>Start: </template>
{it.value.label}
<template lwc:if={it.last}> (current)</template>
</span>
</template>
</nav>
</template>// breadcrumbs.js
import { LightningElement } from 'lwc';
export default class Breadcrumbs extends LightningElement {
crumbs = [
{ id: 'home', label: 'Home' },
{ id: 'shop', label: 'Shop' },
{ id: 'cart', label: 'Cart' }
];
}Here the iterator is named it. The current item is at it.value, so the key is {it.value.id}. The key still goes on the first element inside the loop, here the span.
Use for:each for ordinary lists. Use iterator only when you need first or last.
Dynamic classes per row
Per-row styling follows the same rule as everything else: compute it in JavaScript. A template cannot choose a class with a ternary, so add the class string to each item in the getter.
// taskList.js
import { LightningElement } from 'lwc';
export default class TaskList extends LightningElement {
tasks = [
{ id: 't1', title: 'Write chapter', done: true },
{ id: 't2', title: 'Review chapter', done: false }
];
get displayTasks() {
return this.tasks.map((t) => ({
id: t.id,
title: t.title,
cssClass: t.done ? 'slds-text-color_success' : 'slds-text-color_weak'
}));
}
}<!-- taskList.html -->
<template>
<ul>
<template for:each={displayTasks} for:item="task">
<li key={task.id} class={task.cssClass}>{task.title}</li>
</template>
</ul>
</template>Handling an empty list
An empty array renders no items and no message. To show an empty state, combine the loop with lwc:if and a boolean getter. Both parts read from the same data.
<!-- taskPanel.html -->
<template>
<template lwc:if={hasTasks}>
<ul>
<template for:each={tasks} for:item="task">
<li key={task.id}>{task.title}</li>
</template>
</ul>
</template>
<template lwc:else>
<p>No tasks yet.</p>
</template>
</template>// taskPanel.js
import { LightningElement } from 'lwc';
export default class TaskPanel extends LightningElement {
tasks = [];
get hasTasks() {
return this.tasks.length > 0;
}
}Updating a list so it re-renders
Rendering is only half of the problem. You also have to change the array in a way that the component notices.
- Reassigning the field always triggers a re-render. Building a new array with spread,
map, orfilterand assigning it to the field is the safest approach. - Changing the array in place, for example with
this.tasks.push(...), is observed only when the field is decorated with@track.
// taskPanel.js (adding a task)
import { LightningElement } from 'lwc';
export default class TaskPanel extends LightningElement {
tasks = [{ id: 't1', title: 'Write chapter' }];
addTask() {
const id = `t${this.tasks.length + 1}`;
this.tasks = [...this.tasks, { id, title: 'New task' }];
}
}The id here is derived from the array length. That works for a demo, but it breaks as soon as you delete items, because two tasks can end up with the same id. In real code, take the id from the record, or generate it from a counter that only goes up.
Common errors
- Key on the wrong element. The compiler reports an error, or the list behaves badly. Move
keyto the first element directly inside the loop template. - Missing key. Each item inside
for:eachmust have one. Without it, the template fails to compile. - Duplicate keys. Two items with the same
idproduce wrong updates. Check your data, especially if you merge lists from two sources. - Expressions in the template. Writing
{contact.firstName + ' ' + contact.lastName}fails. Computelabelin the getter. - Calling a method on an item.
{contact.getLabel()}is not allowed. Precompute the value. - Looping over a non-array. If the getter can return
undefined, for example while data is loading, return an empty array instead so the loop has a safe value.
Exercise
A template renders <li key={contact.index}> where index is the item's position in the array. Users can delete rows, and typed text in an input in a row sometimes ends up on the wrong contact after a delete. What is the cause, and how do you fix it?
Show answer
The index is not stable identity. After a delete, every later item gets a new index, so the engine matches old elements to different data and keeps their internal state (such as typed input) in the wrong place. Fix it by keying on a unique, stable property of the record, such as {contact.id}, and keep the key on the first element inside the loop.
Exercise
You need to display each item as "Name (Role)" and highlight managers with a CSS class. Where do you compute these values, and why?
Show answer
In a getter in the JavaScript class. Map the source array to objects that include a label string such as ${name} (${role}) and a cssClass string chosen with a ternary. The template then binds {item.label} and class={item.cssClass}, because LWC templates cannot contain concatenation or conditional expressions.