How does Lightning Web Component JS file work?

JS file is included by default in Lightning Web Component file tree structure and this JS file must be needed to execute Lightning Web Component. The naming convention of this file is componentName.js. JS files are based on ES6 modules.

The structure is:

import { LightningElement } from 'lwc';
export default class WelcomeWindow extends LightningElement {}

Here the componentName is “welcomeWindow“. If you see the welcomeWindow.js file, you can see the class name is WelcomeWindow which is in Pascal case as discussed in previous session. First two lines in the JS file are the default lines provided by Salesforce.com.

import statement is used to import a class or function or variable and export is used to call this class or component from other componentĀ  as per the general web standard rule. Here, import statement imports a custom wrapper of the standard HTML custom element, LightningElement from the core module lwc and export helps to expose your Lightning Web Component. By default, everything is locally scoped to the module in JS file.

Let’s say, we can take the same component mentioned in the previous session. Now, we will try to show welcome message using property which will be set from component js file.

Step 1: We can use the same Lightning Component named “welcomeWindow“, otherwise we need to create new component. First, we will set the metadata XML file to set the visibility in Lightning App Builder or in Lightning Experience.

welcomeWindow.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="welcomeWindow">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Step 2: Then need to focus on HTML file.

welcomeWindow.html

<template>
    <lightning-card title="Welcome My Friends">    
        <lightning-layout>
                <lightning-layout-item flexibility="auto" padding="around-small">                    
                    {welcomeMessage}
                </lightning-layout-item>
            </lightning-layout>
    </lightning-card>     
</template>

Here, we have declared a property called “welcomeMessage“.

Step 3: Then we will update the JS file.

welcomeWindow.js

import { LightningElement } from 'lwc';

export default class WelcomeWindow extends LightningElement {
    welcomeMessage = 'Welcome to LWC Training Class';
}

In this JS file, we have set the property “welcomeMessage” to certain value such as “Welcome to LWC Training Class“.

Result

 

 

 

 

 

Let’s discuss aboutĀ the properties of JS file in the next session.

9,282 total views, 3 views today

Rating: 5.0/5. From 3 votes.
Please wait...
This entry was posted in Lightning Web Component. Bookmark the permalink.

Leave a Reply