SalesforceBlue

Feel the rhythm of Salesforce

LWC

Using Data Attribute In LWC

Consider you have a requirement where you wanted to specify custom attributes on your HTML elements which will be storing some value and later you wanted to use this to derive some logic.

Well, you can achieve this via Data Attributes. Let’s understand this with the below example:

So the ask in this example is to show a greeting message in three different languages when a user clicks the respective button. To achieve this we will be storing the greeting message as a data attribute in the respective button element and will use the same value to display to the user. Please note on any live project this should be handled with proper translation services 🙂

Alright, coming back to our example.

Let’s create a component(LWC) and name it as dataSetExample. Please add the following code to it:

<template>
    <lightning-card title="Data Set Example">

        <div slot="actions">
        <lightning-button onclick={greetingHandler} data-msg="Hello" label="Hello"></lightning-button>
        <lightning-button onclick={greetingHandler} data-msg="Hola" label="Hola"></lightning-button>
        <lightning-button onclick={greetingHandler} data-msg="Namaste" label="Namaste"></lightning-button>
        </div>
        <div class="slds-var-p-around_small lgc-bg">
            {greetingMessage}
        </div>
    </lightning-card>    
</template>
import { LightningElement } from 'lwc';

export default class DataSetExample extends LightningElement {
    greetingMessage;
    
    greetingHandler(event) {
        this.greetingMessage  = event.target.dataset.msg;
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
     <targets>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Let’s understand what we did.

In dataSetExample.html we have specified a custom data attribute by adding data-msg. For declaring any data attribute, you have to add data- to it followed by the name you wanted to give. In our case, we have given data-msg.

In dataSetExample.js event.target.dataset.msg is returning the value of the data-msg attribute.

Data attributes can be used for a variety of purposes to meet your requirements. Feel free to play around with it 🙂

Here is a preview of this component when added to the home page.

Data Set Example

Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *