Sub topic 5
Rendering with the iterator directive
This chapter assumes you can already render a list with for:each, bind class properties with curly braces, and use lwc:if for conditional rendering. It also assumes you know what the key attribute is for. Here you will learn how the iterator directive works, what it gives you that for:each does not, and where it fails.
What the iterator directive does
The iterator directive renders an array like for:each does. The difference is what the template receives on each pass. for:each gives you the current item, and optionally its index. iterator gives you one object per pass, with four properties:
| Property | Type | Meaning |
|---|---|---|
| `value` | any | The current array element |
| `index` | number | Zero-based position of the element |
| `first` | boolean | `true` only on the first element |
| `last` | boolean | `true` only on the last element |
You name that object yourself in the directive. In iterator:it={contacts}, the name is it, and the array is the property contacts on the component class.
<!-- contactList.html -->
<template>
<ul>
<template iterator:it={contacts}>
<li key={it.value.Id}>
{it.value.Name}
</li>
</template>
</ul>
</template>// 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' }
];
}This renders three li elements. Compare it with the for:each version of the same list. The data and output are identical. Only the way you reach the current item changes: contact.Name becomes it.value.Name.
How a single pass works
Each pass creates a small object, binds it to the name you chose, and renders the template body once. The diagram below shows the flow for the three-contact array.
Two points follow from this model.
- The name
itexists only inside the iteration template. It is not a property on your class, and JavaScript cannot read it. - The properties
firstandlastare computed from the array's position. You cannot set them, and they do not look at your data.
Where the key goes
Every iterated element needs a key, and the rule is the same as for for:each. Put key on the first element inside the iteration template, and make its value unique and stable within the list.
With iterator, the key almost always reads it.value.Id, or whichever field uniquely identifies the record.
<template iterator:it={contacts}>
<li key={it.value.Id}>{it.value.Name}</li>
</template>Do not use it.index as the key. The index describes position, not identity. If the user deletes the first contact, every later item gets a new index. The framework then treats each remaining row as a different row. It may rebuild DOM nodes it could have reused, and any state tied to those nodes, such as focus or a typed value, can end up on the wrong item.
If you need more than one element per item, wrap them in a single element that carries the key.
<template iterator:it={contacts}>
<div key={it.value.Id} class="row">
<span class="name">{it.value.Name}</span>
<span class="email">{it.value.Email}</span>
</div>
</template>The key goes on the div, not on the span elements inside it.
Using first and last
The main reason to choose iterator is that first and last are available without extra JavaScript. This chapter shows only the basic use. A later chapter covers layout patterns in detail.
<template>
<ul>
<template iterator:it={contacts}>
<li key={it.value.Id}>
<span lwc:if={it.first}>First: </span>
{it.value.Name}
<span lwc:if={it.last}> (last)</span>
</li>
</template>
</ul>
</template>The output for the three contacts is:
First: Amy Taylor
Ravi Patel
Lena Fischer (last)The lwc:if directive takes a single property or getter. It cannot take an expression like it.index === 0. That limit is why first and last exist as ready-made booleans. Anything that needs real computation, such as "every third row", belongs in JavaScript. That topic comes up in the chapter on preparing display values.
Edge cases to know
These cases are worth testing in your own components.
A one-item list
When the array has one element, it.first and it.last are both true on the same pass. Code that assumes they are mutually exclusive will misbehave. For example, a template that renders a separator whenever it.last is false is fine. A template that renders an opening label on first and a closing label on last shows both on the single item. That is correct, but often not what the designer pictured.
An empty list
With an empty array, the template body never runs. The ul still renders, and it has no children. The directive does not give you a place to show a fallback message. Handle that by checking the list length before the iteration, using a getter and lwc:if. A later chapter in this tutorial covers that pattern fully. A minimal version looks like this:
<template>
<ul lwc:if={hasContacts}>
<template iterator:it={contacts}>
<li key={it.value.Id}>{it.value.Name}</li>
</template>
</ul>
<p lwc:else>No contacts to show.</p>
</template>get hasContacts() {
return Array.isArray(this.contacts) && this.contacts.length > 0;
}Checking Array.isArray first protects against a property that is still undefined, for instance before a wire adapter returns data.
Array changes
The directive reads the array each time the template renders. If you push into the array in place, the component may not re-render. Assign a new array instead, such as this.contacts = [...this.contacts, newContact]. When the new array renders, the keys let the framework match old rows to new ones. Only genuinely new rows are created.
Primitive arrays
You can iterate over an array of strings or numbers, because it.value holds whatever the element is. But a primitive has no Id for a key. If the values are unique, use the value itself as the key.
<template iterator:it={tags}>
<li key={it.value}>{it.value}</li>
</template>If the array can contain duplicates, this produces duplicate keys. Convert the array to objects with unique ids in JavaScript first.
Common errors
The following mistakes come up most often with iterator.
- Using the item name where the object name is needed. Writing
{it.Name}instead of{it.value.Name}givesundefined. The iterator object holds the element undervalue. - Putting the key on the wrong element. If the
keysits on a nested child instead of the first element, the compiler reports an error, or the list misbehaves. - Using an expression in a binding. Writing
{it.index + 1}is invalid. Templates in LWC do not evaluate expressions. If you need a one-based number, add it in JavaScript as part of the data, for instance withmap. - Reusing a name from the class. The iterator name is local to the template. Pick a short name that does not collide with how you refer to other things, such as
itorrow. - Duplicate or missing keys. Duplicates cause rows to be mismatched during updates. A missing key is flagged when the template compiles.
For the expression problem, here is a correct way to show a one-based number.
get numberedContacts() {
return this.contacts.map((contact, i) => ({
...contact,
number: i + 1
}));
}<template iterator:it={numberedContacts}>
<li key={it.value.Id}>{it.value.number}. {it.value.Name}</li>
</template>The getter recomputes whenever the template renders, so the numbers stay correct after adding or removing items.
Summary of the working model
iterator:name={array}renders the template body once per element.- Inside the body,
name.value,name.index,name.first, andname.lastare available. - The first element inside the template needs a
keybound to a unique, stable value such asname.value.Id. - The directive cannot run expressions or show an empty-list message, so precompute values and guard with a getter.
- Replace the array rather than mutating it, so the component re-renders.
Exercise
A list has exactly one item and its template shows "Start" when it.first is true and "End" when it.last is true. What does the user see for that item, and why?
Show answer
The user sees both "Start" and "End". With a single element, the first and last positions are the same, so it.first and it.last are both true on that one pass.
Exercise
A developer writes <li key={it.index}>{it.value.Name}</li> and the list lets users delete rows. What goes wrong, and what should the key be?
Show answer
After a deletion, every later row gets a new index, so the framework can match rows to the wrong data and lose state such as focus or typed input. The key should be a stable unique identifier from the data, such as it.value.Id.
Exercise
You want each row to show its position starting at 1. Why does {it.index + 1} fail, and how do you fix it?
Show answer
LWC templates cannot evaluate expressions, so it.index + 1 is invalid. Compute the number in JavaScript, for example with a getter that maps the array to objects with a number field, and bind {it.value.number}.