Earn a Salesforce AI Certification by IIT + 12-Week Internship Secure Your Spot Today!

Earn a Salesforce AI Certification by IIT + 12-Week Internship Secure Your Spot Today!
Custom Label in Lightning Web Component (LWC) saasguru

Custom Label in Lightning Web Component (LWC) | saasguru

Custom labels in Salesforce Lightning Web Components (LWC) are user-defined text values accessed from any Apex or LWC code. They are critical in application development, especially in scenarios requiring localization, dynamic text values, and maintainability.

One of the key advantages of custom labels is their ability to promote consistency and ease of updates. Since the text is stored in a centralized location, changes to the label automatically propagate throughout the application, eliminating the need to search and replace text in multiple places.

In this blog, you will learn:

  • What Custom labels is
  • Importance of Custom labels in LWC
  • Creating custom labels in LWC with example
  • Advanced Use Cases

Custom Labels In Lightning Web Component(LWC) Example

Step 1: Create Custom Labels in Salesforce

First, you need to create the custom labels in Salesforce.

  1. Navigate to Setup in your Salesforce org.
  2. Go to Custom Labels (found under User Interface or Customize in Setup).
  3. Create two new labels:
  • Label Name: GreetingMessage, Value: “Hello, Welcome to our site!”
  • Label Name: FarewellMessage, Value: “Thank you for visiting, goodbye!”

Step 2: Create the LWC

Now, let’s create the Lightning Web Component.

File: exampleComponent.js

import { LightningElement } from ‘lwc’;

import greetingMessage from ‘@salesforce/label/c.GreetingMessage’;

import farewellMessage from ‘@salesforce/label/c.FarewellMessage’;

export default class ExampleComponent extends LightningElement {

    // Properties to hold the label values

    greeting = greeting message;

    farewell = farewellMessage;

}

In the JavaScript file, we import the custom labels and assign them to component properties using the import statement.

File: exampleComponent.html

<template>

    <div>

        <p>{greeting}</p> <!– Displaying the greeting message –>

        <p>{farewell}</p> <!– Displaying the farewell message –>

    </div>

</template>

In the HTML template, we use the properties to display the label values.

Step 3: Deploy and Test

After creating the component, you would deploy it to your Salesforce org and add it to a page to test it. The component will display the greeting and farewell messages defined in the custom labels.

Also Read – Combobox in LWCsaasguru Salesforce Labs: Real-time Projects for Practice

Advanced Use Cases

Dynamic Language Switching

Dynamic language switching allows your LWC to adapt its displayed labels according to the user’s language preference, enhancing the user experience for a global audience

How to Implement:

  • Set Up Translated Labels: In Salesforce, provide translations for your custom labels for all supported languages.
  • User Language Preference: Salesforce automatically uses the user’s language setting to display the correct label translation.
  • Component Implementation: When you use a custom label in your LWC, Salesforce handles the translation dynamically based on the user’s language setting. There’s no additional coding required for this basic functionality.

Example:

If you have a custom label named GreetingMessage, translated into multiple languages in the Salesforce setup, Salesforce will automatically display the appropriate translation in your LWC based on the user’s language preference.

Incorporating Variables in Labels

Sometimes, you need to display dynamic content within a label (like a user name, date, or any other variable data). Salesforce does not directly support variables in custom labels, but you can achieve this by combining labels with JavaScript string manipulation.

How to Implement:

  • Create Custom Labels with Placeholders: For example, a label with Welcome, {0}! Today is {1}.
  • Replace Placeholders in JavaScript: In your LWC’s JavaScript file, use string replacement to substitute placeholders with dynamic values.

Example Code:

JavaScript File (exampleComponent.js):

import { LightningElement } from ‘lwc’;

import baseLabel from ‘@salesforce/label/c.WelcomeMessage’;

export default class ExampleComponent extends LightningElement {

    get welcomeMessage() {

        const userName = ‘John Doe’; // Dynamic value, e.g., fetched from user data

        const todayDate = new Date().toLocaleDateString();

        return baseLabel.replace(‘{0}’, userName).replace(‘{1}’, todayDate);

    }

}

HTML Template (exampleComponent.html):

<template>

    <p>{welcomeMessage}</p>

</template>

 

Also Read – Salesforce LWC Datatable – Go-To Guide

Importance of Custom Labels in LWC

  • Localization and Internationalization: In today’s global market, applications need to cater to users from various regions, each with their own language preferences. Custom labels in LWC make translating text into different languages simpler without altering the code. This feature mainly benefits multinational companies looking to localize their applications for different markets.
  • Reusability and Maintenance: Custom labels enhance code reusability and ease maintenance. When developers need to update any text, they can do so in one place rather than modifying it in multiple components. This centralized approach to managing text reduces errors and saves development time.
  • Dynamic Content Delivery: Custom labels can be used to deliver dynamic content based on user preferences, roles, or any other criteria defined in Salesforce. This flexibility allows for a more personalized user experience.
  • Avoiding Hard-Coded Text: Hard-coding text directly into components is not a best practice, as it makes localization and updates cumbersome. Custom labels provide a more scalable and manageable approach, keeping the UI text separate from the component logic.
  • Enhanced Collaboration and Consistency: Since custom labels are centralized, they promote consistency across different components and pages of the application. They also make it easier for teams to collaborate, as developers and translators can work on the labels independently of the component development.Online Bootcamps India

Conclusion

A custom label is a key-value pair. The key is the label’s unique name, and the value is the text or message it holds. This value can be translated into multiple languages supported by Salesforce, enabling the creation of multilingual applications. Custom labels can store strings like error messages, form labels, or any other text that might need to be displayed in a Salesforce application.

If you’re eager to deepen your Salesforce skills and connect with a community of like-minded professionals, consider joining our community on Slack. Here, you’ll find a wealth of knowledge, support, and networking opportunities. 

Additionally, saasguru offers hands-on online Salesforce bootcamps, where you can gain practical experience and work on real projects. These bootcamps are designed to provide you with the skills and confidence needed to excel in your Salesforce career.

Whether you’re a beginner or looking to advance your skills, our community and bootcamps are here to support your journey. 

Connect with saasguru today and start transforming your Salesforce expertise!

Table of Contents

Subscribe & Get Closer to Your Salesforce Dream Career!

Get tips from accomplished Salesforce professionals delivered directly to your inbox.

Looking for Career Upgrade?

Book a free counselling session with our Course Advisor.

By providing your contact details, you agree to our Terms of use & Privacy Policy

Unlock Your AI -Powered Assistant

Gain Exclusive Access to Your Salesforce Copilot

Related Articles

Mass Assign User Permission Set in Salesforce

Learn how to efficiently mass assign user permission sets in Salesforce using tools like Data Loader. Save time and ensure accuracy. Read now!

How to Clone a FlexCard in Salesforce

Learn how to clone a FlexCard in Salesforce with this step-by-step guide. Simplify customization and boost efficiency effortlessly!

Salesforce Introduces Agentforce 2.0: Redefining How Work Gets Done

Salesforce introduces Agentforce 2.0, the AI platform transforming digital labor with autonomous agents and seamless workflows. Read now!