Sub topic 10
Handling Clicks on List Items with Data Attributes
A list template renders one element per array item, but you write the click handler once. When the user clicks the third row, the handler has to find out which item that row represents. This chapter shows how to do that by storing the item's identifier in a data-* attribute and reading it back from the event.
This chapter assumes you can already render a list with for:each, give each item a unique key, and bind a method to an event with onclick={handler}. It builds on the decoratedContacts pattern from the previous chapter.
The problem: one handler, many items
Suppose the template renders three contacts. Each <li> has the same onclick={handleSelect}. LWC calls handleSelect with a single argument, the DOM Event, and the handler cannot see the loop variable contact.
The obvious fix does not work:
<!-- Invalid: LWC templates cannot call methods or pass arguments -->
<li key={contact.Id} onclick={handleSelect(contact.Id)}>{contact.Name}</li>An event binding must be a plain reference to a method. Templates do not support function calls, arguments, or inline expressions. The loop variable exists only while the template renders. By the time the user clicks, the only link between the DOM element and your data is whatever you wrote onto the element.
A data-* attribute is that link.
Storing the identifier on the element
Add data-id={contact.Id} to the element that carries the handler. The handler reads it back from the event.
<!-- contactList.html -->
<template>
<ul lwc:if={hasContacts}>
<template for:each={decoratedContacts} for:item="contact">
<li key={contact.Id}
class={contact.cssClass}
data-id={contact.Id}
onclick={handleSelect}>
{contact.Name}
</li>
</template>
</ul>
<p lwc:else>No contacts to show.</p>
<p lwc:if={selectedName}>Selected: {selectedName}</p>
</template>// contactList.js
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
selectedId;
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' },
{ Id: '003C', Name: 'Lena Fischer' }
];
get hasContacts() {
return this.contacts.length > 0;
}
get decoratedContacts() {
return this.contacts.map((contact) => ({
...contact,
cssClass: contact.Id === this.selectedId ? 'selected' : ''
}));
}
get selectedName() {
const match = this.contacts.find((c) => c.Id === this.selectedId);
return match ? match.Name : '';
}
handleSelect(event) {
this.selectedId = event.currentTarget.dataset.id;
}
}The flow is:
- The template renders
data-id="003B"on the second<li>. - The user clicks that row.
handleSelectreceives the event.event.currentTargetis the<li>, anddataset.idis"003B".- Assigning
selectedIdtriggers a re-render. The getterdecoratedContactsruns again and theselectedclass moves to the new row.
How the attribute name maps to dataset
The browser exposes data-* attributes through the element's dataset object. The name is converted by fixed rules, and the value is always a string.
| Attribute in the template | Property on `dataset` |
|---|---|
| `data-id` | `dataset.id` |
| `data-contact-id` | `dataset.contactId` |
| `data-position` | `dataset.position` |
| `data-row-index` | `dataset.rowIndex` |
Write attribute names in lowercase with hyphens in the template. The browser removes the data- prefix and turns each hyphen plus letter into a capital letter.
Because values are strings, a numeric value comes back as text. If you bind data-position={position} from for:index, then dataset.position is "0", not 0. Convert it when you need a number:
handleRowClick(event) {
const position = Number(event.currentTarget.dataset.position);
console.log(this.contacts[position]);
}Comparing "003B" to a Salesforce Id works because both are strings. Comparing "2" to the number 2 with === fails silently.
currentTarget versus target
Both properties point at an element, but they differ when the handler's element has children.
event.currentTargetis the element the handler is attached to. For the example above, it is always the<li>.event.targetis the innermost element that received the click. If the<li>contains a<span>and the user clicks the text,targetis the<span>.
A <span> has no data-id, so event.target.dataset.id returns undefined whenever the click lands on a child. Use currentTarget when the data-* attribute sits on the element that owns the handler.
<li key={contact.Id} data-id={contact.Id} onclick={handleSelect}>
<span class="name">{contact.Name}</span>
<span class="role">{contact.Role}</span>
</li>With this markup, event.currentTarget.dataset.id is correct for a click anywhere in the row. event.target.dataset.id is undefined for clicks on either span.
Handling clicks on a child element
Sometimes the handler is on a child, for example a delete button inside each row. Put the data-* attribute on that button, so currentTarget is the button.
<li key={contact.Id}>
{contact.Name}
<button data-id={contact.Id} onclick={handleRemove}>Remove</button>
</li>handleRemove(event) {
const id = event.currentTarget.dataset.id;
this.contacts = this.contacts.filter((c) => c.Id !== id);
}If you want a click on the button not to also trigger a row-level handler, call event.stopPropagation() in handleRemove.
From the identifier back to the item
The data-* attribute usually holds only the Id. To work with the full record, look it up in your array:
handleSelect(event) {
const id = event.currentTarget.dataset.id;
const contact = this.contacts.find((c) => c.Id === id);
if (!contact) {
return;
}
this.selectedId = id;
this.dispatchEvent(
new CustomEvent('contactselect', { detail: { id: contact.Id } })
);
}Look up the record in the original contacts array rather than in decoratedContacts. The decorated copies contain display-only fields such as cssClass, which the parent usually does not need. Keeping the lookup against the source data also means that display logic stays in one place.
The if (!contact) guard handles the case where the list changed between render and click, for example when a refresh removed that record. Sending only the Id in detail keeps the event small. The parent can decide what else it needs.
Accessibility: use a button for clickable rows
A plain <li> with onclick works for a mouse. It is not focusable and does not respond to the keyboard. For anything users must be able to operate, put a <button> (or a lightning-button) inside the item and attach the handler and data-id to it:
<template for:each={decoratedContacts} for:item="contact">
<li key={contact.Id} class={contact.cssClass}>
<button type="button" data-id={contact.Id} onclick={handleSelect}>
{contact.Name}
</button>
</li>
</template>The handler stays the same. The key still belongs on the <li>, the first element directly inside the iteration template. The data-id goes on the <button>, because that is the element carrying onclick.
The same pattern works on base components. <lightning-button data-id={contact.Id} onclick={handleSelect}> exposes data-id on the host element, and event.currentTarget.dataset.id reads it.
Common errors
dataset.idisundefined. Either the attribute is on a different element than the handler, or you usedevent.targetand clicked a child. Switch tocurrentTargetand check the attribute is on the same element asonclick.- The attribute name does not match.
data-contact-idis read asdataset.contactId. Readingdataset.contact_idordataset['contact-id']returnsundefined. - Using the index as the identifier.
data-position={position}is fine for display or for locating a row in the current array. After a sort, insert, or filter, the same position points to a different record. Prefer the Id for anything that changes data. - Passing arguments in the template.
onclick={handleSelect(contact.Id)}is rejected. Use a data attribute. - Comparing a string with a number. Every
datasetvalue is a string. Convert withNumber()before comparing to numeric fields. - Mutating instead of reassigning. Changing
this.contacts[0].Name = 'x'inside a handler may not produce the update you expect for objects you did not create. Assign a new array, as covered in the update chapter.
Exercise
A list renders <li key={item.Id} data-item-id={item.Id} onclick={handleClick}><b>{item.Name}</b></li>. In handleClick, event.target.dataset.itemId is sometimes undefined. Why does that happen, and what is the fix?
Show answer
When the user clicks the bold text, event.target is the <b> element, which has no data-item-id. When the click lands on the <li> padding, target is the <li> and the value is found. Use event.currentTarget.dataset.itemId, because currentTarget is always the <li> that owns the handler. Note the camelCase conversion: data-item-id becomes itemId.
Exercise
Each row has data-position={position} from for:index, and the handler runs this.items[event.currentTarget.dataset.position]. The lookup works, but a check such as dataset.position === 0 never passes. What is wrong, and why is the Id usually a safer choice than the position?
Show answer
dataset values are strings, so dataset.position is "0" and "0" === 0 is false. Convert with Number(...). A position is only valid for the array as it was rendered. After the list is sorted, filtered, or has items inserted, the same position can refer to a different record. A unique Id keeps pointing at the same record.