Sub topic 12
Nesting one list inside another
This chapter shows how to render a list inside each item of another list, for example accounts that each contain contacts. It assumes you already know for:each, for:item, the key attribute, lwc:if, and how to prepare display values in a getter. Nesting adds no new directive. It does add rules about where keys go, how names are scoped, and how to update data that has more than one level.
The shape of nested data
A nested list starts with nested data. Each outer item holds an array of inner items.
const accounts = [
{
Id: '001A',
Name: 'Acme',
contacts: [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' }
]
},
{ Id: '001B', Name: 'Globex', contacts: [] }
];The outer for:each iterates over accounts. The inner for:each iterates over account.contacts, using the current outer item as its source. The template can read that property directly, because it is a plain property access and not an expression.
Data from a server often arrives flat, with each contact carrying an AccountId. In that case, group it in JavaScript before it reaches the template:
function groupContacts(accounts, contacts) {
return accounts.map((account) => ({
...account,
contacts: contacts.filter((contact) => contact.AccountId === account.Id)
}));
}The template stays simple because the grouping work is done in the class.
A complete nested list
The outer iteration template must have a keyed first element. Put the inner list inside that element. Here the outer element is an li and the inner list is a ul.
<!-- accountContacts.html -->
<template>
<ul>
<template for:each={decoratedAccounts} for:item="account">
<li key={account.Id}>
<h3>{account.Name} ({account.countLabel})</h3>
<ul lwc:if={account.hasContacts}>
<template for:each={account.contacts} for:item="contact">
<li key={contact.Id}
class={contact.cssClass}
data-id={contact.Id}
data-account-id={account.Id}
onclick={handleSelect}>
{contact.Name}
</li>
</template>
</ul>
<p lwc:else>No contacts for this account.</p>
<button data-account-id={account.Id} onclick={addContact}>
Add contact
</button>
</li>
</template>
</ul>
</template>The class below supplies the data and the computed values the template needs:
// accountContacts.js
import { LightningElement } from 'lwc';
export default class AccountContacts extends LightningElement {
selectedContactId;
selectedAccountId;
newContactCount = 0;
accounts = [
{
Id: '001A',
Name: 'Acme',
contacts: [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' }
]
},
{ Id: '001B', Name: 'Globex', contacts: [] }
];
get decoratedAccounts() {
return this.accounts.map((account) => ({
...account,
hasContacts: account.contacts.length > 0,
countLabel: `${account.contacts.length} contacts`,
contacts: account.contacts.map((contact) => ({
...contact,
cssClass: contact.Id === this.selectedContactId ? 'selected' : ''
}))
}));
}
handleSelect(event) {
this.selectedContactId = event.currentTarget.dataset.id;
this.selectedAccountId = event.currentTarget.dataset.accountId;
}
addContact(event) {
const accountId = event.currentTarget.dataset.accountId;
this.newContactCount += 1;
this.accounts = this.accounts.map((account) =>
account.Id === accountId
? {
...account,
contacts: [
...account.contacts,
{
Id: `new-${this.newContactCount}`,
Name: `New Contact ${this.newContactCount}`
}
]
}
: account
);
}
}Several earlier rules show up together here:
- The template cannot run
account.contacts.length > 0, so the getter precomputeshasContactsandcountLabel. - The inner
cssClassis computed per contact inside the getter, which is the prepared-data pattern applied at two levels. - Each button and each contact carries
data-account-id, so the handlers can tell which parent an event belongs to. - The empty inner list gets its own fallback with
lwc:ifandlwc:else, using a flag stored on the outer item.
How the template is evaluated
The diagram shows how one outer item produces its own inner list.
The inner template runs once per outer item, each time with a different array. If there are 3 accounts with 4 contacts each, the engine creates 3 outer elements and 12 inner elements. Cost grows with the total number of rendered nodes, so large two-level lists can get slow. Paginate or filter in JavaScript before you render them.
Keys at both levels
Every iteration template needs a key on its first element, and that includes the inner one. A key must be unique among its siblings, meaning the other items produced by the same iteration. Keys do not have to be unique across the whole component.
| Level | Key | Must be unique among |
|---|---|---|
| Outer `li` | `account.Id` | The other accounts |
| Inner `li` | `contact.Id` | The other contacts in the same account |
In practice, record Ids are globally unique, so this rule is met without effort. It matters when your data is not record data. Suppose each group numbers its own items 1, 2, 3. Those values are fine as inner keys, because the inner lists are separate sibling sets. They would not be fine in a single flat list.
Do not build inner keys from the position. A key such as account.Id + index changes when an item is inserted or removed, which defeats the point of a stable key. If an inner item has no natural identifier, create one when you load the data, as addContact does with new-1, new-2, and so on.
Naming and scope
The outer item stays in scope inside the inner iteration. That is why data-account-id={account.Id} works on a contact element. Two consequences follow:
- Use a different
for:itemname at each level. Reusingitemin both loops is ambiguous, and the template compiler rejects duplicate names in the same scope. - Choose descriptive names such as
accountandcontact, notouterandinner. A handler readingdataset.accountIdis easier to follow than one readingdataset.outerId.
The same applies with the iterator directive. Each level needs its own name, and first and last belong to the iterator that produced them:
<template>
<ul>
<template iterator:acct={decoratedAccounts}>
<li key={acct.value.Id}>
{acct.value.Name}
<ul>
<template iterator:con={acct.value.contacts}>
<li key={con.value.Id}>
{con.value.Name}
<span lwc:if={con.last}> (last contact)</span>
</li>
</template>
</ul>
<hr lwc:if={acct.last} />
</li>
</template>
</ul>
</template>Here con.last is true only for the final contact of each account, and acct.last is true only for the final account.
Updating nested data
A class field that holds an array or object triggers a re-render when you assign a new value to it. It does not trigger one when you change something inside the old value. With two levels, there are two places where this can go wrong. If you push a contact into account.contacts, the accounts field was never reassigned, so the component does not re-render.
The safe pattern is to rebuild each array on the path from the root to the change, and to reuse everything else:
- Map over the outer array.
- For the matching account, return a new object with a new
contactsarray. - For every other account, return the same object unchanged.
- Assign the result to
this.accounts.
addContact above follows these steps. Removing a contact works the same way, with filter in place of the spread:
removeContact(accountId, contactId) {
this.accounts = this.accounts.map((account) =>
account.Id === accountId
? {
...account,
contacts: account.contacts.filter(
(contact) => contact.Id !== contactId
)
}
: account
);
}Because the other accounts keep the same object, and every item keeps the same key, the engine can reuse their elements and change only what differs.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Compiler error about a missing key | The inner iteration's first element has no `key` | Add `key={contact.Id}` to the inner `li` |
| Inner list is stale after adding an item | You mutated `account.contacts` and did not reassign `accounts` | Rebuild the path and assign a new outer array |
| Template error on `account.contacts.length` | The template cannot run expressions | Compute `hasContacts` in a getter |
| Click handler cannot tell which account was clicked | Only the contact Id was stored | Add `data-account-id` on the inner element |
| Selection highlight jumps after a reorder | Keys were built from the index | Use stable Ids as keys |
| Name conflict between loops | The same `for:item` name at both levels | Give each level its own name |
Exercise
In the accounts example, a developer adds a contact with this.accounts[0].contacts.push({ Id: '003Z', Name: 'Zoe Lin' }); and the list on screen does not change. Explain why, and write the corrected statement so that only the first account gets a new contacts array.
Show answer
The accounts field is never reassigned, and the code changes the inner array in place, so the component does not detect a change and does not re-render. Rebuild the path and assign the result: this.accounts = this.accounts.map((account, i) => i === 0 ? { ...account, contacts: [...account.contacts, { Id: '003Z', Name: 'Zoe Lin' }] } : account);. The first account gets a new object and a new contacts array. The other accounts are reused unchanged.
Exercise
A template uses key={contact.Id} on the inner li and key={account.Id} on the outer li. Two different accounts each contain a contact whose Id is '1'. Is this a key problem? Would it be a problem if both contacts were in the same account?
Show answer
It is not a problem across accounts, because keys only need to be unique among siblings from the same iteration, and the two contacts are in different inner lists. It would be a problem inside the same account, because the two li elements would share a key in one sibling set, which makes updates unreliable. Fix that case by giving the items unique Ids when the data is created.