Avi Rai
Data attributes in Lightning Web Components
Hello everyone,
Most of the times we have problem passing information when button clicked or any element is selected in HTML to the javascript in LWC. As we also know that Id selector is of no use in case of LWC. Well, data attributes are here to rescue us in this situation. So let's move further and know how can we use data attributes in LWC.
For instance, we are showing the list of contact records on the UI and we need to capture the information about the selected contact in javascript. Here, we can create the custom attribute by appending any string to "data-" and provide the information to it. Below I have created "data-id", "data-name", "data-title" attributes in the anchor tag to pass some information about selected contact to javascript for further logic. Remember, we can only provide string value to the data attributes.
<template>
<lightning-card title="Example - Data Attributes" icon-name="custom:custom14">
<ul class="slds-m-around_medium">
<template for:each={contacts} for:item="contact">
<li key={contact.Id}>
<a onclick={handleContactClick} data-id={contact.Id} data-name={contact.Name}
data-title={contact.Title}>{contact.Name}, {contact.Title}</a>
</li>
</template>
</ul>
</lightning-card>
</template>
import { LightningElement } from 'lwc';
export default class ExampleDataAttributes extends LightningElement {
contacts = [
{
Id: 1,
Name: 'Amy Taylor',
Title: 'VP of Engineering',
},
{
Id: 2,
Name: 'Michael Jones',
Title: 'VP of Sales',
},
{
Id: 3,
Name: 'Jennifer Wu',
Title: 'CEO',
},
];
handleContactClick(event) {
let contactId,contactName,contactTitle;
[contactId,contactName,contactTitle] = [event.currentTarget.dataset.id,event.currentTarget.dataset.name,event.currentTarget.dataset.title];
alert(`Selected contact - ${contactId}; ${contactName}; ${contactTitle}`);
}
}
Don't forget to notice the template literals and destructuring assignment used in the "handleContactClick" function.
All thoughts are welcome.
Happy learning and stay safe :)