Monday, 27 July 2020

Share Custom labels between Lightning Web Components

We know how to use custom label in lightning web components. What about if you have large list of labels and you want to to use in multiple LWC components? In this post we will talk about best practice to import bulk custom label in LWC and how to create utility class to import same set of label in multiple Lightning web components.

You can create a utility component that imports all the labels and then exposes them bundled together in one object via a method. Then your main component will have a cleaner list of imports.

Step 1) Create Utility Class.


Create a Lightning web component that contains only a single Js file. Like below structure

labelUtility
   ├──labelUtility.js
   └──labelUtility.js-meta.xml

Lets create one common label Utility component.

labelUtility.js
import header from '@salesforce/label/c.Header';
import title from '@salesforce/label/c.title';

const label = {
    header: header,
    title: title
};

export {label};
  • The module should only have a JS file & Metadata file in it, otherwise it will not work.
  • Just like with any Lightning web component, the folder name and the filename must be identical
  • Imports all the labels and then exposes them bundled together with export.

Step 2) How to use shared label Utility


Create new Lightning web component and import Js file with import statement like below

import { label  } from 'c/labelUtility';

Let see the full code.

import { LightningElement,track } from 'lwc';
import { label  } from 'c/labelUtility';
export default class CustomLabelDemo extends LightningElement {
    @track myLabel=label;
}     
  • Import JS file with import

<template>
    <lightning-card  title={myLabel.title} variant="narrow" icon-name="standard:opportunity">
        <p>{myLabel.header}</p>
    </lightning-card>
</template>   


Please share your feedback and comment if there is any better way to implement or your like this post.





21 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Very useful points for beginners. I'm glad you shared it.

    ReplyDelete
  3. Very helpful points for beginners.
    To know more about Salesforce Visit Webnersolutions!

    ReplyDelete
  4. "Looking for Salesforce consultants and integration services? 360 Degree Cloud offers a full suite of Salesforce customization Services and Salesforce CRM Integration. 360 Degree Cloud is serving its customers with the utmost delicacy and efficiency. Give us a chance and see how Salesforce Integration can pave your path to success and glory. Connect with our experts today and get started!
    "

    visit-360degreecloud

    ReplyDelete