Lightning Web Component

How to Use Custom Labels in LWC

Custom Labels in LWC are essential to maintenance, consistency, and dynamism. You could use them to declare a variable that could be modified in the future, meaning you won't have to update the code.

It also could manage more than one language on a single Component, allowing you to modify the text displayed quickly.

Creating a Custom Label in Salesforce to call it from a LWC

Custom Labels in LWC Example

In this example, we will declare some Account names on the custom label to display on the Lightning Web Component so, in the future, we can change it more quickly if we have to.

Declare the Custom Label

First, declare the Custom Label on Setup > Custom Label.

Creating a Custom Label in Salesforce to call it from a LWC

As you can see, they are separated by a "," but you can use whatever character you want.

Import Custom Label in LWC

Once the Custom Label is created, import it on the Lightning Web Component. To do it, you must import it from @salesforce/label/c.{your label name}.

In this case, I used accNames as the name of the variable containing the Custom Label, but you can use whatever name you like.

import { LightningElement } from 'lwc';
import accNames from '@salesforce/label/c.AccountNames';

export default class getCustomLabel extends LightningElement {

}
You must include the c. before the custom label name.

Display the Account Names

Finally, we will create a new array accountNames to store all the names.

The split() method in Javascript will create a new array containing the values from the Custom Label. In this case, we will split it using the ",".

import { LightningElement } from 'lwc';
import accNames from '@salesforce/label/c.AccountNames';

export default class getCustomLabel extends LightningElement {
    accountNames = [];

    connectedCallback(){
        this.accountNames = accNames.split(',');
    }
}
<template>
<lightning-card title="Account Names w/ Custom Label" icon-name="custom:custom14">
    <ul>
        <li for:each={accountNames} for:item="acc" key={acc}>
            <p>{acc}</p>
        </li>
    </ul>
</lightning-card>
</template>

This is how the Lightning Web Component looks like using the Custom Label imported.

Creating a Custom Label in Salesforce to call it from a LWC

Now, if I modify the Custom Label, the changes will be reflected on that LWC without modifying the code. That's why the Custom Labels are very useful to create dynamic components.