Sub topic 8
Rendering lists with for:each and key
This chapter assumes you can bind properties with { } and write a getter, as covered earlier in this tutorial. Here you will render an array as a list and see why each item needs a key.
The working model
LWC templates cannot run expressions, so you cannot map or filter an array inside the HTML. Instead you prepare the array in JavaScript, usually in a getter, and loop over the result with the for:each directive.
Prepare the data in a getter
The getter below turns each contact into a small object with a unique id and a ready-made label. The template then binds only to simple properties.
// 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}`
}));
}
}Loop in the template
<!-- contactList.html -->
<template>
<ul>
<template for:each={displayContacts} for:item="contact">
<li key={contact.id}>{contact.label}</li>
</template>
</ul>
</template>Three attributes matter here:
for:each={displayContacts}names the array. It must be a property or getter, not an expression.for:item="contact"names the variable for the current element. You use it inside the loop as{contact.label}.key={contact.id}gives each rendered element an identity.
The loop runs over a <template> tag, which renders nothing itself. Only the <li> elements appear in the DOM.
Why the key matters
When the array changes, the framework compares the old and new lists. The key lets it match each item to its existing DOM element, so it can reuse, move, or remove elements instead of rebuilding the whole list. Without stable keys, input values, focus, and child component state can end up attached to the wrong row.
Follow these rules:
- Put
keyon the first element directly inside thefor:eachtemplate, not on the<template>tag. - Use a string or number, such as a record Id.
- Make it unique among siblings in that loop.
- Make it stable. The same item should produce the same key on every render.
Optional: the index
If you need the position of an item, add for:index:
<template for:each={displayContacts} for:item="contact" for:index="position">
<li key={contact.id}>{position}: {contact.label}</li>
</template>The index is fine for display. Do not use it as the key when items can be added, removed, or reordered, because the same index will then point to different items over time.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| Missing `key` | Compile error | Add `key` to the first element in the loop |
| `key` on the `<template>` tag | Compile error | Move it to the first child element |
| Using `for:index` as the key | Wrong state after reordering | Use a stable id from the data |
| Looping over an expression such as `contacts.map(...)` | Template does not compile | Move the logic into a getter |
| Duplicate keys | Unpredictable updates | Make ids unique before rendering |
Keep the getter cheap
The getter runs each time the template renders. A map over a short list is fine. For large lists, avoid sorting or filtering inside the getter on every render. Compute the result once when the source data changes, store it in a field, and loop over that field.
Exercise
A template contains <template for:each={rows} for:item="row" for:index="i"><li key={i}>{row.name}</li></template>. Users can delete rows from the middle of the list. What problem can this cause, and how do you fix it?
Show answer
The key is the index, so after a deletion the remaining rows shift to new indexes and keys point at different items. The framework may reuse the wrong DOM elements, which can leave input values or child component state on the wrong row. Fix it by using a stable unique value from the data, such as key={row.id}.