Sub topic 10
Handling clicks on list items with data attributes
This chapter assumes you can render a list with for:each, set a key on each item, and bind a class property in a template. It builds on the earlier chapter on preparing display values in JavaScript. Here you will learn how a click handler can tell which list item was clicked.
The problem: one handler, many items
A list renders the same markup many times. Every <li> uses the same handler, so the handler needs a way to learn which item fired the event. An LWC template cannot pass arguments, so onclick={handleSelect(contact)} is not valid. Instead, store the item's identifier in a data-* attribute and read it from the event.
Writing the data attribute
A data-* attribute is a custom HTML attribute whose name starts with data-. In LWC you can bind it to the current item:
<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>
</template>The attribute data-id holds the record Id. The key is a separate attribute that LWC uses internally. It is not readable from the handler, so you still need data-id.
Reading the attribute in the handler
The browser exposes every data-* attribute through the element's dataset property. The name after data- becomes a property, so data-id is read as dataset.id.
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
selectedId;
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' }
];
get hasContacts() {
return this.contacts.length > 0;
}
get decoratedContacts() {
return this.contacts.map((contact) => ({
...contact,
cssClass: contact.Id === this.selectedId ? 'selected' : ''
}));
}
handleSelect(event) {
this.selectedId = event.currentTarget.dataset.id;
}
}When the user clicks, handleSelect stores the Id in selectedId. The getter decoratedContacts runs again, and the matching item receives the selected class.
Why currentTarget and not target
event.target is the innermost element that received the click. event.currentTarget is the element the handler is attached to. If the <li> contains a <span> or an icon and the user clicks it, target is that child, which has no data-id. currentTarget is always the <li>.
Data attribute naming rules
The browser converts attribute names to property names. Follow these rules to avoid surprises.
| Attribute in the template | Property on `dataset` |
|---|---|
| `data-id` | `id` |
| `data-contact-id` | `contactId` |
| `data-position` | `position` |
Always write attribute names in lowercase. Hyphens turn the next letter into uppercase on dataset.
Common mistakes
- Treating the value as a number. Every
datasetvalue is a string. If your Ids are numbers, convert them withNumber(...)before comparing with===. - Using
event.target. It works until the item contains a child element, then fails in a confusing way. - Reading
key. The handler cannot readkey. Usedata-id. - Mutating the item instead of reassigning. Setting a property on a tracked object may not refresh your computed values the way you expect. Store the selected Id and let a getter derive the display state.
Finding the item from its Id
Often the handler needs the whole record, not only its Id. Look it up in the source array:
handleSelect(event) {
const id = event.currentTarget.dataset.id;
this.selectedId = id;
const selected = this.contacts.find((contact) => contact.Id === id);
this.dispatchEvent(new CustomEvent('select', { detail: selected }));
}This keeps the template simple and the data in one place.
Exercise
A list item contains a <span> with the contact's name. A developer reads event.target.dataset.id in the click handler and gets undefined when the user clicks the name text. Why does this happen, and what is the fix?
Show answer
event.target is the <span> the user clicked, and the data-id attribute is on the parent <li>. Use event.currentTarget.dataset.id, because currentTarget is the element the handler is attached to, which is the <li>.
Exercise
You add data-contact-id={contact.Id} to each <li>. What expression reads the value in the handler?
Show answer
event.currentTarget.dataset.contactId. The hyphen followed by a letter becomes a camelCase property name.