Sub topic 2
Rendering an array with for:each
This chapter assumes you can build a basic Lightning Web Component (LWC) with an HTML template and a JavaScript class that extends LightningElement. You should also know how to bind a class property with curly braces and how Array.prototype.map works. The focus here is the for:each directive: what it expects, what it produces, and where it fails.
What for:each does
A template cannot contain a JavaScript loop. LWC templates have no for statement and no expressions such as {items.map(...)}. To render an array, you use a directive, which is a special attribute the template compiler understands. for:each repeats a block of markup once for every element in an array.
The directive goes on a <template> tag. That tag is not rendered to the DOM. It only marks the block to repeat. Three attributes matter:
| Attribute | Purpose | Required |
|---|---|---|
| `for:each={array}` | The array to iterate over. Must be a bound property or getter. | Yes |
| `for:item="name"` | The variable name for the current element inside the block. | Yes |
| `for:index="name"` | The variable name for the zero-based position. | No |
The value of for:each must be a binding in curly braces that points to a class property or getter. You cannot write a literal array or call a function with arguments there.
A minimal example
Start with the data. The component holds an array of plain objects. Each object has a unique Id.
// contactList.js
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' },
{ Id: '003C', Name: 'Lena Fischer' }
];
}Now the template. The for:each directive sits on a <template> tag, and the element inside it carries a key.
<!-- contactList.html -->
<template>
<ul>
<template for:each={contacts} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>The browser receives this markup:
<ul>
<li>Amy Taylor</li>
<li>Ravi Patel</li>
<li>Lena Fischer</li>
</ul>The key attribute does not appear in the output. The framework reads it during rendering and then uses it internally. The next chapter sections on keys explain why it matters. For now, treat it as mandatory.
How the iteration scope works
Inside the for:each block, the name you gave to for:item is a variable available only in that block. In the example above, contact refers to the current element on each pass. You read its fields with dot notation: {contact.Name}, {contact.Id}.
Some rules follow from this.
- The item variable is read-only in the template. You cannot assign to it.
- The name must be a valid identifier. Pick a singular noun, such as
contactfor a list calledcontacts. - The variable does not exist outside the block. Referencing
contactafter the closing</template>produces a compile error or an empty value. - Only property access is allowed.
{contact.Name}works.{contact.Name.toUpperCase()}does not, because templates cannot call functions or evaluate expressions.
The last point is the one that surprises people coming from React or Vue. If you need a computed value for each item, you compute it in JavaScript. A later chapter covers that pattern.
The key goes on the first element
LWC requires a key on the first element inside the iteration template. It must be a direct child of the <template for:each> tag. If you wrap the content in a <div>, the key goes on that <div>.
<template>
<template for:each={contacts} for:item="contact">
<div key={contact.Id} class="row">
<span>{contact.Name}</span>
</div>
</template>
</template>Putting the key on the <span> here would be an error, because the <div> is the first element. The compiler checks this when you deploy or run the local development server, and it reports a message about a missing key on the iterated element.
The value of the key must be a string or a number, and it must be unique among the siblings in that one list. It does not have to be unique across the whole page. Keys are covered in detail in a later chapter, so this chapter only uses Id fields, which are a good default when the data comes from Salesforce records.
Getting the position with for:index
Add for:index when you need the zero-based position of the current element.
<template>
<ul>
<template for:each={contacts} for:item="contact" for:index="position">
<li key={contact.Id} data-position={position}>{contact.Name}</li>
</template>
</ul>
</template>With the three contacts above, position is 0, 1, and 2. The value is a number. It is zero-based, so showing it to users as "1, 2, 3" requires adding one in JavaScript, because the template cannot do {position + 1}.
Use the index for display or for a data attribute. Do not use it as the key. The index describes where an item sits now, not which item it is. If the array is reordered or an item is removed from the front, every index shifts, and the framework can no longer tell which DOM element belongs to which record. The pitfalls chapter returns to this.
What the data must look like
for:each works on arrays. It does not accept plain objects or Map and Set instances directly. If you have an object, convert it first with Object.entries or Object.values.
// settingsList.js
import { LightningElement } from 'lwc';
export default class SettingsList extends LightningElement {
settings = { theme: 'dark', language: 'en', density: 'compact' };
get settingEntries() {
return Object.entries(this.settings).map(([name, value]) => ({
name,
value
}));
}
}<!-- settingsList.html -->
<template>
<ul>
<template for:each={settingEntries} for:item="entry">
<li key={entry.name}>{entry.name}: {entry.value}</li>
</template>
</ul>
</template>Here the getter turns an object into an array of objects. Each entry has a name that is unique, so it works as the key.
Elements that are primitives, such as an array of strings, are a special case. You can iterate them, but {contact.Id} has no meaning on a string, so you have nothing natural to use as a key. Wrap the values in objects, or use the string itself as the key when the strings are guaranteed to be unique.
<template>
<template for:each={tags} for:item="tag">
<span key={tag}>{tag}</span>
</template>
</template>This works only if every tag appears once. Two identical tags produce duplicate keys.
Data from Salesforce
Data from @wire or Apex often arrives as an array of record objects, and each record has an Id. You can pass data straight to for:each once it is defined. Before the wire service responds, data is undefined, and for:each over undefined renders nothing. It does not throw. That is convenient on first load, but it means a missing result and an empty result look the same unless you check for them. The chapter on empty lists shows how to tell them apart.
Records from the wire service are frozen, which means you cannot change their fields. When you need extra fields, build new objects with the spread operator rather than mutating the originals.
get rows() {
return (this.records || []).map((record) => ({
...record,
label: `${record.Name} (${record.Id})`
}));
}Common failure messages
| Symptom | Likely cause |
|---|---|
| Compile error about a missing key | The first element inside the iteration has no `key`, or the `key` is on a nested element. |
| Console warning about duplicate keys | Two items share the same key value. |
| List renders nothing, no error | The array is `undefined`, empty, or you bound the wrong property name. |
| `for:each` rejected at compile time | The value is not a curly-brace binding, or the attribute is on an element other than `<template>`. |
The rendering flow
The diagram shows what happens each time the template renders. The framework reads the bound array, then repeats the block once per element, using the key to identify each rendered item.
Summary of the rules
- Put
for:eachandfor:itemon a<template>tag. - Bind
for:eachto an array held by a property or getter. - Give the first element inside the block a unique
key. - Read item fields with dot notation only. Compute anything else in JavaScript.
- Use
for:indexfor display, never for the key.
Exercise
A developer writes this template and gets a compile error. What is wrong, and how do you fix it? <template for:each={contacts} for:item="contact"> <li>{contact.Name.toUpperCase()}</li> </template>
Show answer
There are two problems. First, the <li> has no key, so add key={contact.Id} to it. Second, templates cannot call methods such as toUpperCase(). Compute the value in JavaScript, for example by mapping contacts to objects that include an upperName field in a getter, and bind {contact.upperName}. (Also, the for:each template here is the root of the file, so wrap it in a <template> root and put the <li> elements inside a <ul> for valid markup.)
Exercise
You have a Map stored in a class property named scores. How do you render its entries with for:each, and what do you use as the key?
Show answer
Convert the Map to an array of objects in a getter, for example Array.from(this.scores, ([name, score]) => ({ name, score })), and bind for:each to that getter. Use the name field as the key, provided the Map keys are unique, which they always are in a Map.