Anatomy of Lightning Web Component

In the introductory blog post, we learnt about the ‘What-Why-How’ of a new paradigm of UI development in Salesforce called as Lightning Web Component (LWC) framework. It is next in the evolutionary phase after the Aura framework and Salesforce has made big bets on it by going open source.

In this post, we are going to go a level further and explore the various building blocks that make up a lightning web component. So let’s get started

Every Lightning web component is made up of 3 basic files –

  • A HTML file – This file defines the structure of the component.
  • A Javascript file – This file establishes the behaviour of the component.
  • A metadata file – This is a configuration file which houses the metadata information.

Now lets look them in detail

HTML

Every Lightning component must have a HTML file with a root tag <template>. The naming convention of the HTML file is as follows

<component>.html

For eg : If you decide to name your lightning web component as ‘myComponent’ then the html file will look like – myComponent.html

The actual markup of the HTML goes inside the <template> tags as below

<!-- myComponent.html -->
<template>
    <!-- In goes the HTML markup of your supercalifragilisticexpialidocious component!!!! -->
</template>

On the browser, when the component is rendered, the <template> tag is replaced with actual name of the component. So the above component will be rendered as <c-my-component>(kebab case – Delicious !).

Now a very common scenario during UI development is to ‘Show/Hide’ certain parts of the component (markup) based on condition. This can be easily done using what is called as ‘directive’ in modern web standard parlance. One of the very commonly used directive is ‘if:true|false’ directive.

We are going to look at this in detail in the upcoming posts, but I just wanted to give you a sneak peek of what it looks like in HTML

The below component is composed of 2 templates. The second template is composed inside the parent template. Pay attention to the if:true={shouldHelloBeVisible} directive used in the second template which is used to dynamically show/hide the ‘Hello!’ message.

<!-- myComponent.html -->
<template>
    <lightning-card title="ConditionalRendering" icon-name="custom:custom14">
        <div class="slds-m-around_medium">
            <lightning-input type="checkbox" label="Say Hello" onchange={handleChange}></lightning-input>
            <template if:true={shouldHelloBeVisible}>
                <div class="slds-m-vertical_medium">
                    Hello!
                </div>
            </template>
        </div>
    </lightning-card>
</template>

We are going to look at how to set the ‘shouldHelloBeVisible’ property in the next section – Javascript

Javascript

Every lightning component must have have a Javascript file. It defines the HTML element. The naming convention of a Javascript file is as follows

<Component>.js

So if we have a component ‘myComponent’ then the javascript file name will be myComponent.js

Every lwc UI component must include a Javascript file with the below code

import { LightningElement } from 'lwc';
export default class MyComponent extends LightningElement {
// Your paracetamoxyfrusebendroneomycin code goes here!!
}

There is lot going on in those few lines of code. Let me break it for you. So

  1. import { LightningElement } from ‘lwc’ – In this line we are importing ‘LightningElement’ from the ‘lwc’ module. ‘lwc’ is a standard core module of Lightning Web Component framework. ‘LightningElement’ is the custom wrapper of the standard HTML element. Think of it like this – Before you can create an fusion ice-cream dessert, you are first bringing a vanilla (LightningElement) scoop from your fridge (lwc module) on your plate

2. export default class MyComponent extends LightningElement – Once you have the vanilla ice-cream on your plate, you are going to extend it with more flavours to create that perfect combination. So in this line we extend the base ‘LightningElement’ and give a name to our class (more about the class name in a second). With ‘export default’ keyword, we are also exporting this class so that other classes could eventually import it and then reuse/repurpose it for own use.

Javascript class names must have a Pascal naming convention. For eg : If the file name is ‘myComponent.js’ then the class name will be ‘MyComponent’ (first letter of each word is capitalized)

Javascript files in Lightning Web Component framework usually contains –

  • The component’s public API via public properties and methods annotated with @api.
  • Private properties
  • Event handlers

Let’s look at the Javascript file for our myComponent (described earlier) which sets the ‘shouldHelloBeVisible’ property to conditionally render the template

// myComponent.js
import { LightningElement } from 'lwc';

export default class MyComponent extends LightningElement {
    shouldHelloBeVisible = false;

    handleChange(event) {
        this.shouldHelloBeVisible = event.target.checked;
    }
}

Pretty easy ! Isn’t it ? For a start – Yes !

Now our HTML and Javascript file are ready for action. But we need one last file to glue it all together – The metadata configuration file.

Configuration

Every component must have have configuration file. It defines the metadata values of the component and also the design configuration needed for Lightning App Builder.

The naming convention of the Configuration file is as below

<component>.js-meta.xml

So for a ‘myComponent’ the configuration file will be named as myComponent.js-meta.xml

If you don’t include a configuration file while defining the component and then try to push it in a Salesforce org, you will get the below error

Cannot find Lightning Component Bundle <component_name>

Now let’s look at the configuration file for our component created for conditional rendering

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

Here the target tags define where all in Lightning Experience we can use this component. So the above configuration file enables our component to be dragged on the App Page, Record Page as well as Home Page.

If isExposed is false, the component is not exposed to Lightning App Builder or Experience Builder.

But the above files – HTML, Javascript and Configuration are only the must haves? Yes ! You can optionally also define below files for your lightning web component

  • An optional CSS File – To style a component, create a style sheet in the component bundle with the same name as the component. If the component is called myComponent, the style sheet is myComponent.css. The style sheet is applied automatically.
  • An optional SVG File – To include an SVG resource as a custom icon for your component, add it to your component’s folder. It must be named <component>.svg. If the component is called myComponent, the svg is myComponent.svg. You can only have one SVG per folder.
  • Other Javascript Files – Use these JavaScript files to share code.
  • Test Files – You can test your lightning web components using Jest framework. Test files must have names that end in “.js”, and the recommendation is to use “.test.js”.

Finally all of these files have to be bundled together under a component folder like below

To recap – Every lightning web component is basically structured around – A HTML file, A Javascript file and a Configuration File. We will continue to explore some advance topics on Lightning Web Component framework in coming posts. Till then – Stay safe and happy learning !

Lightning Web Components – Introduction (In Pictures)

This blog is primarily intended to serve as a refresher and a quick primer to know and then speak about LWC to anyone (customers, partners, fellow developers and in community). I have always tried to conceive complex ideas and concepts with visualizations. It helps with the retention and gives you talking points to speak if needed.

If you have been in the Salesforce ecosystem from its nascent stage, you would have had a firsthand experience of the transformation that has occurred in the platform’s frontend technology. From the primitive era of ‘S-controls‘ to the more popular ‘VisualForce‘ and then ‘Aura‘. (Or Lightning Components)

Continuing with this evolution, Salesforce has introduced Lightning Web Component framework and finally committed to the web standards. It has broken the proprietary shell and has gone open source. This is really a bold step!

But what this change in the UI tech brought to the platform and to the developers ? And the answer is – It has paved ways for both increased performance and ease for developers to implement it.

But this also meant for developers to keep up to the changing pace and climb that steep learning curve. But at Salesforce and with our Ohana, we have always coped up. Haven’t we ? And this time, it shall be no different !

Duh ! Another framework ? Another web language ? When I started learning LWC, I had 3 questions in my mind. We will cover the introduction to Lightning Web Component framework by answering these 3 questions.

  • Why Lightning Web Component was needed ?
  • What is Lightning Web Component framework ?
  • How can you implement Lightning Web Component framework ?

Why Lightning Web Component framework ?

The answer is – The web stack as we know has changed significantly between the time Aura component framework was brewing and the modern times. The pink part that you see are the web standards and the green represents the things that a proper Javascript framework handles.

The web stack as we know has changed significantly between the time Aura component framework was brewing and the modern times

As you can see during 2014, the web standards comprised of mostly – Standard Elements, Rendering, Events and the use of ECMA Script 5. As a result, most of the heavy-lifting had to be done by the framework (green part) like – Custom elements, Data Services etc. This resulted into proliferation of frameworks. There came JQuery, Angular, React, Ember etc (I can go on and on…). Each with its own unique way of handling the green part. Hence if your project chose React framework, you had to hire a React Developer. You see the problem ?

A lot of innovation happened in the web standards since then which resulted into a much more robust and a modern stack. Most of the things that these frameworks solved, found their way into the standards ! (Look at the image in 2019. More of pink and less of green!). This standardization paves way for a new breed of frameworks. Their job now will not be to fill the gaps which standards lacked but to provide more specialized services specific to the platform.

What exactly is Lightning Web Component Framework?

Lightning Web Component Framework is Salesforce’s take on this new breed of framework which is built on web standards. It involves the use of Custom Elements, Shadow DOM, Templates, Decorators, Modules and other new ECMA Script 7 and beyond language constructs. Try and remember these terms because you are going to hear a lot about them in your journey to master Lightning Web Component Framework.

The components that we develop using this framework are called as lightning web components (hereon referred to as lwc). Just like we had a bundle for the aura components which contained all the files used to implement a lightning component, we need files to form a lwc.

There are 3 files which you need (mandatorily) to create a lwc.

  • A Javascript File (.js)
  • A Html File (.html)
  • A Meta XML file (.js-meta.xml)

For an introduction, you just need to know the basic structure of a lwc. We are going to discuss in detail about all these files (and few additional ones too) in our next blog.

But there would be another question looming in your mind – Can lightning web components and aura components coexist ? Are they interoperable ? And the answer is – YES !

Lightning web components and aura components can work together but with one caveat

Aura components can contain lightning web components but lightning web components cannot contain aura components 

How can we create and implement LWC ?

Visual Studio Code + Salesforce CLI + Plugins + Scratch/Non Scratch Orgs

You will need tools to build lwc. Primarily you will need the following

  • Visual Studio Code and plugins – Salesforce’s go to IDE now for developing everything – including Apex and Aura components
  • Salesforce CLI – Command Line Tool which can run and understand the sfdx commands
  • Salesforce Orgs – Scratch Orgs (if DX is enabled) Or Non Scratch Orgs (Regular Dev Environment)

Please follow the trailhead to setup these tools. You can also find how to use VS code if you are using a Non DX Or a DX here.

This blog is primarily intended to serve as a refresher and a quick primer to know and then speak about LWC to anyone (customers, partners, fellow developers and community). I have always tried to conceive complex ideas and concepts with visualizations. It helps with the retention and gives you talking points to speak if needed.

As I said, this is just an introduction to lwc and we are going to deep dive in it with upcoming blog posts. The next blog post is ‘Anatomy of a lightning web component’. Stay tuned and happy learning!