How to access Custom Labels in Lightning Web Components?

This is going to be a short article. In this article we will learn how to access custom labels in Lightning Web Components.

We will use the same code which we have used in How to align radio group horizontally in LWC?

Here are the steps to access custom labels in Lightning Web Components.

  • First of all you have to create a custom label.
  • Then we have to import the custom label. In order to import the custom label we have to use @salesforce/label in the import statement.
  • Once you have imported the custom label you can use it in LWC HTML or JS.

Have a look at the code base.

import { LightningElement } from 'lwc';
import radioButtonHorizontalStyle from '@salesforce/resourceUrl/radioButtonHorizontalStyle'
import {loadStyle} from 'lightning/platformResourceLoader'

import Radio_Group_Title from '@salesforce/label/c.Radio_Group_Title';
export default class RadioButtonGroupHorizontalAlign extends LightningElement {
    radioGroupTitle = Radio_Group_Title;
    options = [
        { label: 'Male', value: 'Male' },
        { label: 'Female', value: 'Female' }
        
    ];

    renderedCallback(){
        Promise.all([
            loadStyle(this,radioButtonHorizontalStyle)
        ])
    }
}

As you can see above we have imported Radio_Group_Title from @salesforce/label/c.Radio_Group_Title. Don’t forget to use the namespace else you will get an error.

<template>
    <lightning-card title={radioGroupTitle}>
        <div class="slds-p-around_medium">
            <lightning-radio-group class="customRadioCls"
            options={options}
            name="radioGroup"
            label="Gender">
            </lightning-radio-group>
        </div>   
    </lightning-card>
</template>

Here in above HTML code you can see we have set the title attribute of the lightning-card from the custom label which we have imported in Javascript.

We hope now you know how to access custom label in lightning web components. If you have any doubt then let us know in the comment below.

Leave a Comment