Sub topic 6
Detecting the first and last item
This chapter assumes you can write a basic for:each loop with a key, bind class properties with curly braces, and use lwc:if in a template. It also assumes you know Array.prototype.map. Here you will use the iterator directive to find the first and last item in a list. You will also see how to get the same result with for:each when you need to.
Why templates need help with first and last
Many layouts treat the ends of a list differently. A comma list drops the comma after the final name. A table adds a top border to the first row only. A menu gives the last entry a different style.
An LWC template cannot evaluate expressions. You cannot write {index === 0} or lwc:if={index === contacts.length - 1}. A binding can only point to a property, a getter, or a property of an object. So the template needs the answer to arrive as data. There are two ways to get it:
- The
iteratordirective suppliesfirstandlastflags for every pass. - You compute your own flags in JavaScript and loop with
for:each.
What the iterator directive gives you
The iterator directive takes a name after the colon, such as iterator:it. In each pass, it is an object with four properties:
| Property | Meaning |
|---|---|
| `value` | The current array element |
| `index` | The zero-based position of the element |
| `first` | `true` only on the first element |
| `last` | `true` only on the last element |
Here is the template from the earlier chapters, now using the flags:
<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>It needs this class, which is the same one for:each used:
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' }
];
}The output has "First: " before Amy Taylor and " (last)" after Lena Fischer. Ravi Patel gets neither label.
Three details matter here:
- The
keyis still required. It goes on the first element inside the iterator template, here theli, and it reads fromit.value, not fromit. - You reach the data through
it.value. Writing{it.Name}gives you nothing, becauseNamebelongs to the item, not to the iterator object. firstandlastare plain booleans, so they work directly withlwc:if,lwc:elseif, andlwc:else.
The diagram shows what happens on each pass.
Using last to place separators
A common use of last is a separator that appears between items but not after the final one. This component prints a comma-separated list of names ending in a period:
<template>
<p>
<template iterator:it={names}>
<span key={it.value.id}>
{it.value.label}<span lwc:if={it.last}>.</span><span lwc:else>, </span>
</span>
</template>
</p>
</template>import { LightningElement } from 'lwc';
export default class NameList extends LightningElement {
names = [
{ id: 'n1', label: 'Amy' },
{ id: 'n2', label: 'Ravi' },
{ id: 'n3', label: 'Lena' }
];
}This renders Amy, Ravi, Lena.
The lwc:else element must be the next sibling after the lwc:if element. If you put text or another element between them, the template fails to compile. That is why the label comes before the pair and the two spans sit directly next to each other.
Marking the first item
The same pattern works for the first item. A table might want a different class on the first row. Because templates cannot build strings from conditions, use two branches:
<template>
<ul>
<template iterator:it={contacts}>
<template lwc:if={it.first}>
<li key={it.value.Id} class="highlight">{it.value.Name}</li>
</template>
<template lwc:else>
<li key={it.value.Id}>{it.value.Name}</li>
</template>
</template>
</ul>
</template>This works, but it duplicates the li, and the duplication grows with the markup. For more than one or two differences, compute a class name in JavaScript instead, as the next section shows.
Getting first and last with for:each
The for:each directive exposes the item and, with for:index, the position. It has no first or last flag. To reach the same result, add the flags to your data before the template sees it. This is the "prepared list data" pattern from earlier in the tutorial:
import { LightningElement } from 'lwc';
export default class ContactRows extends LightningElement {
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' },
{ Id: '003C', Name: 'Lena Fischer' }
];
get rows() {
const lastIndex = this.contacts.length - 1;
return this.contacts.map((contact, index) => {
const isFirst = index === 0;
const isLast = index === lastIndex;
return {
...contact,
isFirst,
isLast,
cssClass: [
'row',
isFirst ? 'row-first' : '',
isLast ? 'row-last' : ''
]
.filter(Boolean)
.join(' ')
};
});
}
}<template>
<ul>
<template for:each={rows} for:item="row">
<li key={row.Id} class={row.cssClass}>{row.Name}</li>
</template>
</ul>
</template>The getter returns new objects, so the original contacts array stays untouched. The class string is built once per item in JavaScript, so the template needs no conditional branches. This is the main advantage of the approach. The cost is extra code in the class.
Edge cases
The flags describe the array you pass in, so they behave in predictable ways at the boundaries.
- One item. The single element has both
firstandlastset totrue. Check your layout with a one-item list. A separator rule such as "comma unless last" works, but a rule like "first gets a heading, last gets a footer" will show both on the same element. - Empty array. The iterator never runs, so no element is rendered and no flag is read. Handle this with a separate check, as the chapter on empty lists covers.
- Filtered or sorted lists. If a getter filters or sorts the array,
firstandlastrefer to the position in that result. They do not refer to the original data. This is usually what you want, because it matches what the user sees. nullorundefined. If the property is not an array, the directive has nothing to loop over. Initialize list properties to[]rather than leaving them undefined.- Changing arrays. When you assign a new array, the iterator recalculates the flags for the new content. If an item is added at the end, the old last item loses
last, and the new one gains it. With stable keys, LWC updates the existing elements rather than rebuilding them.
Common mistakes
- Writing
{it.index === 0}. This is not valid in a template. Useit.first, or compute a flag in JavaScript. - Putting the key on the wrong element. The key goes on the first element inside the iterator template. A key on a nested child will not satisfy the directive.
- Using
it.lastoutside the loop. The nameitexists only inside theiteratortemplate. A header or footer outside it cannot read these flags. - Breaking an
lwc:if/lwc:elsepair. Any element between the two will cause a compile error. - Mutating the array in place. Pushing to
this.contactsmay not trigger a re-render of a plain property in every case. Assign a new array, such asthis.contacts = [...this.contacts, item], so the flags are recalculated.
Quick comparison
| Need | Best choice |
|---|---|
| Show a label only on the first or last item | `iterator` with `lwc:if` |
| Separator between items, none after the last | `iterator` with `lwc:if` and `lwc:else` |
| Several computed values per item, including position flags | `for:each` with a `map` in a getter |
| Position number for display only | `for:each` with `for:index` |
The next chapter builds on this table to give decision criteria for choosing between the two directives.
Exercise
A list component uses iterator:it={tags} and must show each tag followed by a comma, except the last tag, which is followed by nothing. Write the markup inside the iterator template, assuming each tag has an id and a label. What happens when tags contains only one item?
Show answer
Use <span key={it.value.id}>{it.value.label}<span lwc:if={it.last}></span><span lwc:else>, </span></span>. A simpler form is <span key={it.value.id}>{it.value.label}<span lwc:if={it.last}>.</span><span lwc:else>, </span></span> if an ending mark is wanted. The lwc:else span must directly follow the lwc:if span. With one item, it.last is true on the first and only pass, so no comma is rendered. That single item is also first.
Exercise
Why can a for:each template not simply compare for:index with 0 to detect the first item, and what is the usual fix?
Show answer
Templates cannot evaluate expressions, so index === 0 is invalid. The usual fix is to compute flags in JavaScript, for example with map((item, index) => ({ ...item, isFirst: index === 0 })) in a getter, and loop over that prepared array. Alternatively, switch to iterator, which provides first and last.
Exercise
A list shows three items, and the user adds a fourth by running this.items = [...this.items, newItem]. Which items have it.last equal to true before and after the update, and why should the key not be it.index?
Show answer
Before the update, the third item is last. After the update, the fourth item is last and the third is not, because the iterator recalculates the flags for the new array. The key should not be it.index because it identifies a position, not an item. If items are inserted or reordered, the same index points to different items, and LWC may reuse elements incorrectly.