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.

customLabels.json
1{
2    "ChatHeaderTitle": {
3        "en": "Chat",
4        "es" : "Charlar",
5        "fr" : "Chatte"
6    },
7    "ChatHeaderRequestTranscript": {
8        "en": "Request Transcript",
9        "es" : "Solicitar transcripción",
10        "fr" : "Demander une transcription"
11    },
12    "ChatHeaderEndConversation" : {
13        "en": "End conversation",
14        "es" : "Terminar la conversacion",
15        "fr" : "Mettre fin a la conversation"
16    }
17}

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.

customChatHeader.js
1import { LightningElement, api, track } from "lwc";
2import customLabel from "@salesforce/resourceUrl/customLabels";
3
4export default class CustomChatHeader extends LightningElement {
5     ...
6     @track
7     labels = {};
8
9     ...
10     connectedCallback() {
11         this.getCustomLabels();
12     }
13
14     ...
15
16     getCustomLabels() {
17        try {
18            const language = this.configuration.language;
19            let allLabels;
20            let request = new XMLHttpRequest();
21
22            request.open("GET", customLabel, false);
23            request.send(null);
24
25            allLabels = JSON.parse(request.responseText);
26
27            // Get label translations by language
28            for (let labelName in allLabels) {
29                this.labels[labelName] = allLabels[labelName][language];
30            }
31        } catch {
32            console.log("Error getting label translations");
33        }
34     }
35}