Sub topic 9
Rendering a list of children with for:each
This chapter assumes you can write a basic Lightning web component and that you know how @api properties and template bindings work. You should also be comfortable with arrays and arrow functions in JavaScript.
Why lists need a loop
A parent often holds an array of records and needs one child component for each record. You don't write each child by hand. You use the for:each directive on a <template> tag. It repeats the markup inside it once for each item in the array.
The pattern has three parts:
for:each={tasks}names the array, which is a field or getter in the parent's JavaScript class.for:item="task"names the variable that holds the current item.key={task.id}gives each rendered element a unique identifier.
A worked example
The child is taskCard, which exposes heading and priority with @api. The parent loops over its tasks and passes each item's values down.
// taskBoard.js (parent)
import { LightningElement } from 'lwc';
export default class TaskBoard extends LightningElement {
tasks = [
{ id: 'T-1', name: 'Write documentation', priority: 'high' },
{ id: 'T-2', name: 'Review pull request', priority: 'normal' },
{ id: 'T-3', name: 'Update release notes', priority: 'low' }
];
}<!-- taskBoard.html (parent) -->
<template>
<template for:each={tasks} for:item="task">
<c-task-card
key={task.id}
heading={task.name}
priority={task.priority}>
</c-task-card>
</template>
</template>The <template for:each> tag is not rendered in the page. Only the three c-task-card elements appear. Each one receives its own heading and priority, taken from the current item.
Rules for the key
The key attribute lets the framework track which element belongs to which item. When the array changes, it can then add, remove or move elements without rebuilding all of them.
- Put
keyon the outermost element inside the loop. In the example that isc-task-card. If you wrap the child in adiv, the key goes on thediv. - Use a string or number that is unique within the list and stable over time, such as a record ID.
- Don't use the array index as the key. If items are reordered or removed, the index moves to a different item, and the framework can attach the wrong element to the wrong data.
- Write
key={task.id}as an expression. A literal string such askey="task.id"gives every element the same key.
How updates reach the children
The loop is re-evaluated when the parent's array is replaced. Each child then receives updated values through its public properties, as covered in the earlier chapter on updates. If you want the list to change, assign a new array instead of editing the old one in place:
// taskBoard.js (parent)
addTask(newTask) {
this.tasks = [...this.tasks, newTask];
}
removeTask(idToRemove) {
this.tasks = this.tasks.filter((task) => task.id !== idToRemove);
}Because each child is matched by its key, existing cards keep their state and only the new card is created.
Passing derived values
Template expressions can't contain logic such as {task.priority.toUpperCase()}. If the child needs a computed value, add it to each item before rendering:
get displayTasks() {
return this.tasks.map((task) => ({
...task,
label: `${task.id}: ${task.name}`
}));
}Then loop over displayTasks and bind heading={task.label}. The spread operator copies the original fields, so the source array stays unchanged.
Common mistakes
| Symptom | Likely cause |
|---|---|
| Compile error about a missing key | `key` is absent or is not on the outermost element in the loop |
| Wrong card shows after a reorder | The array index was used as the key |
| Child shows no data | The binding uses the wrong name, such as `{item.name}` when `for:item` is `task` |
| List doesn't update after a change | The array was edited in place instead of being reassigned |
Exercise
A parent renders <c-task-card key={task.id} heading={task.name}> inside for:each={tasks} for:item="task". A teammate proposes replacing the key with the loop index so that the key is always a number. Why is this a bad idea, and what should the key be?
Show answer
When the list is reordered, filtered or has items removed, an index points to a different item than before, so the framework can reuse an element for the wrong data. The key should be a unique, stable value from the data, such as task.id.
Exercise
The parent calls this.tasks.push(newTask) but the page doesn't show the new card. What should it do instead?
Show answer
Assign a new array, for example this.tasks = [...this.tasks, newTask];, so the parent's field changes and the template re-renders.