Sub topic 9
Rendering a list of children with for:each
This chapter assumes you can already pass a single value to a child with @api and a template binding. It also assumes you know that a child treats received values as read-only. Here you will apply those ideas to a list, so that one array in the parent becomes many child components.
The problem: one array, many children
A task board rarely has a fixed number of cards. The parent holds an array, and the template must create one c-task-card for each item. Writing the tags by hand does not work, because the array length is only known at run time. The for:each directive repeats a block of markup once per array item.
// taskBoard.js (parent)
import { LightningElement } from 'lwc';
export default class TaskBoard extends LightningElement {
tasks = [
{ id: 't1', name: 'Write documentation', priority: 'high' },
{ id: 't2', name: 'Review pull request', priority: 'normal' },
{ id: 't3', name: 'Update dependencies', 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 child is the same taskCard component from earlier chapters, with @api heading and @api priority. It does not know it is inside a loop. It receives its two properties exactly as it would from a single static tag.
The parts of the directive
Three pieces make the loop work.
for:each={tasks}names the array. The value in braces must be a property or getter of the parent class that returns an array (or another iterable).for:item="task"names the variable that holds the current item. This is a string, not an expression. Inside the loop you read it as{task.name}.key={task.id}goes on the outermost element inside the loop. In this example that isc-task-card.
The wrapping <template for:each> tag produces no element in the DOM. Only the children appear.
Why the key matters
The framework uses the key to match each rendered child to its array item when the array changes. With stable keys, the engine can reuse an existing c-task-card when an item moves, and it removes only the child whose item was deleted. Without them, it cannot tell which child belongs to which item.
The rules for keys:
- The key must be a string or a number.
- It must be unique among the siblings in that loop. It does not need to be unique across the whole page.
- It must be stable. The same item should get the same key every time the list renders.
- It goes on the outermost element inside the loop, not on the
<template for:each>tag.
An id from your data is the best key. If the items come from Salesforce records, use Id.
<!-- Wrong: key on the wrapping template tag -->
<template for:each={tasks} for:item="task" key={task.id}>
<c-task-card heading={task.name}></c-task-card>
</template><!-- Right: key on the first element inside the loop -->
<template for:each={tasks} for:item="task">
<c-task-card key={task.id} heading={task.name}></c-task-card>
</template>Do not use the array index as the key. If an item is inserted at the top, every index shifts. Each child is then matched to a different item than before, which wastes work and can leave stale internal state in the children.
If you wrap the child in another element, the wrapper takes the key:
<template for:each={tasks} for:item="task">
<li key={task.id}>
<c-task-card heading={task.name} priority={task.priority}></c-task-card>
</li>
</template>Here key is on the li, and the c-task-card inside it does not need one.
Each child gets its own copy of the binding
Inside the loop, {task.name} is evaluated per item. That makes it a dynamic binding, so the update rules from earlier chapters apply to every child. If the parent replaces the tasks array, or reassigns a field the loop reads, the framework re-renders the loop and updates the children that need it.
The one-way data flow rule also still applies. Every task object the child sees through heading or a similar property is the parent's data. If you pass the whole object (task={task}), the child receives a read-only view of it. Assigning this.task.priority = 'high' inside the child fails. If the child needs to change anything, it must copy first or tell the parent.
Passing the whole item or individual fields
You have two options for what to hand each child.
| Approach | Markup | Use when |
|---|---|---|
| Individual fields | `heading={task.name} priority={task.priority}` | The child has a small, clear interface and does not care about the data's shape. |
| Whole object | `task={task}` | The child needs many fields from the same record, or the shape may grow. |
Individual fields keep the child reusable, because it does not depend on your data model. The whole-object approach saves markup, but the child must know the property names. If the child changes the object's contents, remember the copy rule: the setter should store a copy, as in the TaskList example from the getters and setters chapter.
Computing values for the loop
Template expressions in LWC are limited to property access. You cannot write {task.name.toUpperCase()} or {task.priority === 'high'} in the markup. When the child needs a derived value, build it in the parent's JavaScript, in a getter that maps the source array.
// taskBoard.js (parent)
import { LightningElement } from 'lwc';
export default class TaskBoard extends LightningElement {
rawTasks = [
{ id: 't1', name: 'Write documentation', priority: 'high', done: false },
{ id: 't2', name: 'Review pull request', priority: 'normal', done: true }
];
get tasks() {
return this.rawTasks.map((task) => ({
...task,
label: `${task.name}${task.done ? ' (done)' : ''}`,
isUrgent: task.priority === 'high'
}));
}
}<!-- taskBoard.html (parent) -->
<template>
<template for:each={tasks} for:item="task">
<c-task-card
key={task.id}
heading={task.label}
priority={task.priority}>
</c-task-card>
</template>
</template>The getter returns new objects, so the original rawTasks array is never altered. This also makes a good habit: derive display data in one place and keep the markup simple.
Using iterator for first and last
for:each gives you only the current item. If you need to know whether the item is the first or last one, for example to add a divider between cards, use the iterator directive instead. The iterator variable exposes value, index, first and last.
<template>
<template iterator:it={tasks}>
<div key={it.value.id}>
<hr if:false={it.first} />
<c-task-card
heading={it.value.name}
priority={it.value.priority}>
</c-task-card>
</div>
</template>
</template>Note three differences from for:each:
- The directive is
iterator:it, whereitis a name you choose. - You read the item through
it.value. - The key goes on the outermost element inside the loop, here the
div.
Rendering an empty list
When tasks is an empty array, the loop renders nothing and no error occurs. If the array is undefined or null, the loop also renders nothing, but you will usually want to show a message. Add a getter and a conditional:
get hasTasks() {
return Array.isArray(this.tasks) && this.tasks.length > 0;
}<template>
<template lwc:if={hasTasks}>
<template for:each={tasks} for:item="task">
<c-task-card key={task.id} heading={task.name}></c-task-card>
</template>
</template>
<template lwc:else>
<p>No tasks yet.</p>
</template>
</template>The test goes in a getter because you cannot write tasks.length > 0 in the markup.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Compile error about a missing key | No `key` on the first element in the loop | Add `key={item.id}` to that element. |
| Compile error about the key's location | `key` placed on `<template for:each>` | Move it to the first element inside. |
| Children show stale data after a reorder | Index used as the key | Use a stable id from the data. |
| Children are recreated on every update | Keys change between renders, for example random values | Generate ids once, when the data is created, not in the getter. |
| `{task.name.toUpperCase()}` fails to compile | Expressions are not allowed in templates | Compute the value in a getter. |
| Child throws when it edits a received item | The item is read-only in the child | Copy it in a setter before changing it. |
Where this fits
Rendering a list is the parent's side of the contract. The child still only declares @api properties and reads them. Data flowing back, such as "the user clicked this card", needs a custom event, which a later chapter covers.
Exercise
A parent template contains the code below. It fails to compile. Name the problem and write the corrected markup. <template for:each={tasks} for:item="task"> <li> <c-task-card key={task.id} heading={task.name}></c-task-card> </li> </template>
Show answer
The key is on c-task-card, but the outermost element inside the loop is the li, so the key must be on the li. Corrected markup:
<template for:each={tasks} for:item="task">
<li key={task.id}>
<c-task-card heading={task.name}></c-task-card>
</li>
</template>
Exercise
Your parent holds tasks as an array of objects with name and done fields. The child c-task-card should show the heading "Write docs (done)" for finished tasks. Why can't you write that in the loop's markup, and where should the logic go?
Show answer
LWC templates allow only property access, not expressions such as a ternary or string concatenation. Build the label in a parent getter that maps the array, for example get tasks() { return this.rawTasks.map(t => ({ ...t, label: t.done ? ${t.name} (done) : t.name })); }. Then bind heading={task.label} inside the loop.