Create an Object That Contains Label Translations JSON File for a Static Resource

Create a JSON file that includes label translations. Upload this JSON file in Static Resources in Salesforce Setup. Alternatively, create the object directly in the LWC Javascript file.

{
    "ChatHeaderTitle": {
        "en": "Chat",
        "es" : "Charlar",
        "fr" : "Chatte"
    },
    "ChatHeaderRequestTranscript": {
        "en": "Request Transcript",
        "es" : "Solicitar transcripción",
        "fr" : "Demander une transcription"
    },
    "ChatHeaderEndConversation" : {
        "en": "End conversation",
        "es" : "Terminar la conversacion",
        "fr" : "Mettre fin a la conversation"
    }
}

Here’s an example of our static resource in the code snippet for an LWC component. The function getCustomLabels creates an object of labels for the snippet language.

import { LightningElement, api, track } from "lwc";
import customLabel from "@salesforce/resourceUrl/customLabels";

export default class CustomChatHeader extends LightningElement {
     ...
     @track
     labels = {};

     ...
     connectedCallback() {
         this.getCustomLabels();
     }

     ...

     getCustomLabels() {
        try {
            const language = this.configuration.language;
            let allLabels;
            let request = new XMLHttpRequest();

            request.open("GET", customLabel, false);
            request.send(null);

            allLabels = JSON.parse(request.responseText);

            // Get label translations by language
            for (let labelName in allLabels) {
                this.labels[labelName] = allLabels[labelName][language];
            }
        } catch {
            console.log("Error getting label translations");
        }
     }
}