Sub topic 3
Handling List Items in LWC
Assume you know basic HTML and JavaScript, including arrays and map(), and can create an LWC with an HTML template and a JavaScript class.
Handling clicks with data attributes
A data-* attribute stores a small piece of information on an HTML element. In an LWC list, store the record ID on each item. Read it with event.currentTarget.dataset.
<template>
<ul>
<template for:each={contacts} for:item="contact">
<li key={contact.Id}
data-id={contact.Id}
onclick={handleSelect}>
{contact.Name}
</li>
</template>
</ul>
<p>Selected: {selectedId}</p>
</template>import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
selectedId;
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' }
];
handleSelect(event) {
this.selectedId = event.currentTarget.dataset.id;
}
}currentTarget is the element with the handler. target might be a child element clicked inside that element, so currentTarget is safer.
Updating a list so it re-renders
Assign a new array when adding, removing, or replacing items. The spread operator copies the existing items into a new array.
addContact() {
this.contacts = [
...this.contacts,
{ Id: '003C', Name: 'New Contact' }
];
}Nesting one list inside another
Each repeated level needs its own key. The outer key identifies the account, and the inner key identifies the contact.
<template>
<template for:each={accounts} for:item="account">
<section key={account.Id}>
<h2>{account.Name}</h2>
<ul>
<template for:each={account.contacts} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</section>
</template>
</template>Common mistakes and fixes
| Mistake | Fix |
|---|---|
| Missing `key` | Put a unique, stable key on the first element inside each iteration. |
| Using an array index as a key | Use a record ID instead. Indexes change when items move. |
| Mutating the existing array | Assign a new array with spread, `filter()`, or `map()`. |
| Reading `event.target.dataset` | Read `event.currentTarget.dataset` when the handler is on the list item. |
| Using template expressions for calculations | Compute display values in JavaScript getters or `map()`. |
Exercise
A list item has data-id={contact.Id} and onclick={handleSelect}. Which expression reads its ID reliably?
Show answer
event.currentTarget.dataset.id.