Sub topic 3
Using the current item and for:index
This chapter covers the two variables that for:each gives you on every pass: the current item and its position. You should already know how an LWC component pairs an HTML template with a JavaScript class, how to bind a property with curly braces, and how for:each renders an array. This chapter looks at what those variables are, where they can be used, and what they cannot do.
What each pass of the loop provides
The for:each directive sits on a <template> tag and takes the array in curly braces. Two more attributes name the variables the template can read inside that loop:
| Attribute | Value you write | What it creates |
|---|---|---|
| `for:each` | `{members}`, a binding to an array | The list to loop over |
| `for:item` | `"member"`, a plain string | A variable holding the current array element |
| `for:index` | `"position"`, a plain string | A variable holding the current zero-based position (optional) |
for:item and for:index take quoted names, not curly braces. You are choosing a new variable name, not binding an existing value. Writing for:item={member} is a common mistake, and the compiler rejects it.
For each element, the template renders its contents once. Inside that content, member refers to the element for that pass and position refers to its index. Outside the iteration template, neither variable exists.
Reading properties of the current item
The item variable behaves like any object reference in the template. Use dot notation to read its properties:
<template>
<ul>
<template for:each={members} for:item="member">
<li key={member.Id}>{member.Name}, {member.Title}</li>
</template>
</ul>
</template>Here is a component class that supplies the data:
// rosterList.js
import { LightningElement } from 'lwc';
export default class RosterList extends LightningElement {
members = [
{ Id: '003A', Name: 'Amy Taylor', Title: 'Engineer' },
{ Id: '003B', Name: 'Ravi Patel', Title: 'Designer' },
{ Id: '003C', Name: 'Lena Fischer', Title: 'Manager' }
];
}Three points about the item variable:
- It is the actual element of the array, not a copy.
member.Namereads theNameof the object stored inthis.members. - You can pass it to a child component, for example
<c-member-card member={member}></c-member-card>. - You choose the name. Pick one that describes a single element (
member,account,row), so that{member.Name}reads naturally.
The key attribute goes on the first element inside the iteration template, and its value comes from the item. Here it is key={member.Id}. The next chapter explains why keys matter and what makes a good one. For now, use a unique identifier from the data.
Names are strings, so choose valid identifiers
The names in for:item and for:index must be valid JavaScript-style identifiers. They cannot contain hyphens or spaces. for:item="team-member" fails, while for:item="teamMember" works. Use camelCase, the same convention as component properties.
Using for:index
Add for:index when the template needs the position of an item. The value is a number that starts at 0 and increases by 1 on each pass:
<template>
<ul>
<template for:each={members} for:item="member" for:index="position">
<li key={member.Id} data-position={position}>
{member.Name}
</li>
</template>
</ul>
</template>With three members, the rendered li elements carry data-position="0", data-position="1" and data-position="2".
You can bind the index in text ({position}) or in an attribute, as above. A common use is a data-* attribute, so that an event handler can find out which row was clicked.
Reading the index in a handler
HTML attributes are strings, so dataset.position returns "1", not 1. Convert it before using it as an array index:
// rosterList.js
import { LightningElement } from 'lwc';
export default class RosterList extends LightningElement {
selectedName = '';
members = [
{ Id: '003A', Name: 'Amy Taylor', Title: 'Engineer' },
{ Id: '003B', Name: 'Ravi Patel', Title: 'Designer' },
{ Id: '003C', Name: 'Lena Fischer', Title: 'Manager' }
];
handleClick(event) {
const position = Number(event.currentTarget.dataset.position);
this.selectedName = this.members[position].Name;
}
}The matching template adds the click handler and shows the result:
<template>
<ul>
<template for:each={members} for:item="member" for:index="position">
<li key={member.Id} data-position={position} onclick={handleClick}>
{member.Name}
</li>
</template>
</ul>
<p lwc:if={selectedName}>Selected: {selectedName}</p>
</template>The handler uses event.currentTarget, which is the li the listener is attached to. If li held child elements, event.target could point at one of them, and its dataset would not have position.
Why the index is not the key
for:index is tempting as a key, because it is always present and always unique within one pass. Do not use it. A key identifies an item across renders. If the list is reordered, the item that was at position 0 moves to position 2, but the index-based key stays attached to position 0. LWC then reuses the wrong elements, which can leave stale text, lost focus or mixed-up input values in rows. Keys come from the data, and the index is for display and positioning. The next chapter explains this in detail.
Templates cannot run expressions
The curly braces in an LWC template accept a property path, such as member.Name or position. They do not accept expressions. All of these are invalid:
<li key={member.Id}>{position + 1}. {member.Name}</li>
<li key={member.Id}>{member.First + ' ' + member.Last}</li>
<li key={member.Id} class={position % 2 === 0 ? 'even' : 'odd'}>{member.Name}</li>This matters for for:index, because the first thing most people want is a 1-based number ("1. Amy Taylor"). The template cannot add 1. There are two ways to handle it:
- Compute the value in JavaScript and bind the result.
- Accept the zero-based number in the UI. This is rarely what users want.
Precomputing a display value
Use map in a getter to build a new array where each element carries the extra values the template needs:
// rosterList.js
import { LightningElement } from 'lwc';
export default class RosterList extends LightningElement {
members = [
{ Id: '003A', First: 'Amy', Last: 'Taylor' },
{ Id: '003B', First: 'Ravi', Last: 'Patel' },
{ Id: '003C', First: 'Lena', Last: 'Fischer' }
];
get rankedMembers() {
return this.members.map((member, index) => ({
...member,
rank: index + 1,
fullName: `${member.First} ${member.Last}`,
rowClass: index % 2 === 0 ? 'even' : 'odd'
}));
}
}<template>
<ol>
<template for:each={rankedMembers} for:item="member">
<li key={member.Id} class={member.rowClass}>
{member.rank}. {member.fullName}
</li>
</template>
</ol>
</template>The map callback receives the element and its index, which is the same information for:index gives the template. Here the template needs no for:index at all, because every value it displays is already on the item. As a rule, use for:index when the template only needs to pass the position along (for example, into a data-* attribute). Use map when the template needs a value derived from the position.
The spread syntax (...member) copies the existing properties into a new object, so the original array is not changed. The getter runs again whenever a tracked value it reads changes, so the list stays current.
Gotchas with item data
- Missing properties render as empty.
{member.Title}on an object withoutTitleshows nothing, with no error. If a field is blank, check the spelling and capitalization of the property name first, for exampleNameversusname. - Nested properties need care.
{member.Account.Name}fails ifAccountis undefined for some rows. Flatten the value in JavaScript (accountName: member.Account?.Name) or guard it withlwc:if. - Data from
@wireis read-only. Objects returned by a wire adapter are frozen. Assigning tomember.rankthrows an error in strict mode. Build new objects with spread, as shown above. - Variable names are local.
positionexists only inside the iteration template. A handler in JavaScript cannot read it. Pass it through adata-*attribute, as shown earlier. - Only the first element gets the key. If the iteration template holds several sibling elements, the
keygoes on the first one. Elements after it do not need their own.
Summary of when to reach for each tool
| Need | Use |
|---|---|
| Show a property of the current element | `{item.property}` |
| Give the handler the position | `for:index` plus `data-*` attribute |
| Show a 1-based number or other derived text | A getter with `map` |
| Identify the element for a handler | `data-id={item.Id}` |
| Unique identity of a row across renders | `key={item.Id}`, never the index |
Exercise
A template renders <li key={member.Id}>{position + 1}. {member.Name}</li> inside for:each={members} for:item="member" for:index="position", and it fails to compile. Why does it fail, and how do you show a 1-based number?
Show answer
Curly braces in an LWC template accept only property paths, not expressions, so position + 1 is invalid. Compute the number in JavaScript. For example, add a getter get rankedMembers() { return this.members.map((member, index) => ({ ...member, rank: index + 1 })); }, iterate over rankedMembers, and write {member.rank}. {member.Name}.
Exercise
A click handler reads event.currentTarget.dataset.position and uses it directly as this.members[position]. It sometimes returns undefined or the wrong member. Name two causes and one fix.
Show answer
First, dataset.position is a string. Array indexing with "1" works in JavaScript, but arithmetic such as position + 1 produces "11", so convert with Number(). Second, if the template renders a sorted or filtered copy of the array, the index no longer matches the position in this.members. The fix is to store item.Id in data-id and look up the item by Id, for example with this.members.find((m) => m.Id === id).