How to use custom labels in lwc salesforce.

Custom Labels are very useful to save your time and help us manage code redundancy . You can refer custom label in VF page and lighting component as well , how ? we will give you can simple and easy way to use custom labels in you lwc component.

Refer this link to see how to make use of custom label into VF page.

You can create a custom label from your local VS code project or from your salesforce org. here I have this CustomLabels.labels-meta.xml file which contains my custom labels.

CustomLabels.labels-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<CustomLabels xmlns="http://soap.sforce.com/2006/04/metadata">
    <labels>
        <fullName>Demo_Label_1</fullName>
        <language>en_US</language>
        <protected>true</protected>
        <shortDescription>Test Label</shortDescription>
        <value>I am Demo custom Label !</value>
    </labels>
</CustomLabels>

Once you create a custom label you have to import that into your component.

Customlabel.js

import { LightningElement,track } from 'lwc';
import Demo_Label_1 from '@salesforce/label/c.Demo_Label_1';

export default class CustomLabel extends LightningElement {
    @track customLabelValue = Demo_Label_1;
}

Here I have imported my Demo_Label_1 and stored that into customLabelValue this local variable .Now we can refer this customLabelValue variable anywhere in our component .

CustomLabel.html

<template>
    <div class="slds-card">
        <h1>{customLabelValue}</h1>
    </div>
</template>

This is how you can use custom labels into your lwc component.

How the code works

  1. You create the label, either in Setup under Custom Labels or in the CustomLabels.labels-meta.xml file of your project.
  2. In the component JavaScript you import it with the path @salesforce/label/c.LabelName. The c is the default namespace. For a managed package label, use the package namespace instead of c.
  3. You store the imported value in a field and show it in the HTML template.

Points to note

  • The label value is available as soon as the component loads, and it follows the language of the user when translations exist in Translation Workbench.
  • You do not need @track for the field. A plain field is enough.
  • Group your labels in one object to keep the HTML tidy.

Grouping several labels

import { LightningElement } from 'lwc';
import Demo_Label_1 from '@salesforce/label/c.Demo_Label_1';
import Demo_Label_2 from '@salesforce/label/c.Demo_Label_2';

export default class CustomLabel extends LightningElement {
    labels = { demo1: Demo_Label_1, demo2: Demo_Label_2 };
}
<template>
    <h1>{labels.demo1}</h1>
    <p>{labels.demo2}</p>
</template>

FAQ

How do I use the same label in Apex?
Write System.Label.Demo_Label_1.

Can I change a label value without deploying code?
Yes. Edit the label in Setup. Components that use it show the new value.

Leave a Reply