Lightning Web Components (lwc)

Lightning Web Components is one of the Salesforce’s great findings of today’s evolving web standards.  It is a lightweight framework(thin layer of specialized services) built on top of the web standards. Because of its very nature of coexistence and interoperability, it can be used along with aura components, which means Aura components  can also include lightning web components.

As of today, LWC is a pre-release feature of Salesforce. In order to use it we need to use a pre-release org. This can be implemented in both Scratch and non-scratch orgs.  For explaining the concept here we will be creating a component named as “searchContacts” in a scratch org. This component will search the contacts based on the user input and render the results on the component.

Pre-requisites:

Before we start into the details of LWC and implement the concepts in a real working example, we need to have out environment and set up ready. As mentioned earlier, since LWC is a pre-release feature we would need to setup Salesforce DX in a pre-release environment and visual studio. Please follow the steps in the following trailhead module for the setup.

Set Up Your Salesforce DX Environment

Set Up Visual Studio Code

Once the setup is done you are ready to develop the brand new “Lightning Web Components”. Before we start with the implementation, we would like to discuss about the Decorators a little bit, because you would need to use them while you develop your own components.

Decorators:

LWC supports the following decorators:

Api :  To expose a public property, decorate it with @api. Public properties define the API for a component. Public properties are reactive. If the value of a reactive property changes, the component’s template rerenders any content that references the property.

Track : To track a private property’s value and rerender a component when it changes, decorate the property with @track. Tracked properties are also called private reactive properties.

Wire: To read Salesforce data, Lightning web components use a reactive wire service. When the wire service provisions data, the component rerenders. Components use @wire in their JavaScript class to specify a wire adapter or an Apex method.

Prior to their use, all the above decorators must be imported from lwc in javascript as below.

import { LightningElement,<Decorator Name> } from ‘lwc’;

Implementation:

Okay, so we now have our environment ready and visual studio configures. We also know which decorators are available to us and where to use those. Let’s get back to work guys 😉

Creating Project in VS

  1. Open Visual Studio, press Command + Shift + P on a Mac or Ctrl + Shift + P on Windows.
  2. Type SFDX and Select SFDX: Create Project.
  3. Enter searchContactsLWC as the project name, and press Enter.
  4. Select a folder
  5. Click Create Project. Visual Studio will create the base project setup for you and you will see it as below

Authorize a Dev Hub:

When you are setting up DX for the first time, you would need to authorize your dev hub with the visual studio, you can skip this step if you have already authorized your pre-release environment.

  1. Open Visual Studio, press Command + Shift + P on a Mac or Ctrl + Shift + P on Windows.
  2. Type SFDX and Select SFDX: Authorize a Dev Hub.
  3. Log in using your pre-release Dev Hub org credentials.Click Allow

Creating the Lightning Web Component:

In the project tree, Go to “lwc” folder , right click and select “sfdx: Create Lightning Web Component”. Enter the folder/Component name as you wish, here it is searchContacts. It creates 3 files inside the lightning web component such as .html, .js and .xml files.

Enter the below code snippet in searchContacts.html

<template>

        <lightning-card title="ContactSearch" icon-name="custom:custom57">
    
            <div class="slds-m-around_medium">
                <lightning-input type="search" class="slds-m-bottom_small" label="Contact Search" value="{searchKey}" onchange="{changeHandler}"></lightning-input>
                <p class="slds-m-bottom_small">
                        <lightning-button label="Load Contacts" onclick="{handleLoad}"></lightning-button>
                </p>
                <template if:true="{contacts}">
                    <template for:each="{contacts}" for:item="contact">
                    <lightning-layout vertical-align="center" key="{contact.Id}">
                        <lightning-layout-item padding="around-small">
                            <p>{contact.Name}</p>
                            <p>{contact.Title}</p>
                            <p><lightning-formatted-phone value="{contact.Phone}"></lightning-formatted-phone></p>
                        </lightning-layout-item>
                    </lightning-layout>
                    </template>
                </template>
            </div>
            <template if:true="{errors}">
                <div class="slds-p-around_medium">
                <lightning-icon icon-name="utility:error"></lightning-icon>
                <div class="slds-p-around_small"></div>
                    <template for:each="{errors}" for:item="error">
                        <p key="{error.message}">{error.message}</p>
                    </template>
                </div>
            
            </template>    
        </lightning-card>    
    </template>

Code Snippet for searchContacts.js

import { LightningElement, track } from 'lwc';
import findContacts from '@salesforce/apex/ContactSearchController.findContacts';

export default class SearchContacts extends LightningElement {
    @track contacts;
    @track errors;
    @track searchKey = '';

    changeHandler(event) {
        this.searchKey = event.target.value;
    }

    handleLoad() {      
        const searchKey = this.searchKey;
        //Invoke using ApexImperativeMethod approach
        findContacts({ searchKey })
            .then(result => {
                this.contacts = result;
                this.error = undefined;
            })
            .catch(error => {
                this.errors = error;
                this.contacts = undefined;
            });

    }
}

Code Snippet for searchContacts.css

lightning-input {
    position: relative;
    border: solid 1px #ecebea;
    border-radius: 4px;
    display: block;
    padding: 2px;
}

lightning-input:before {
    color: #dddbda;
    position: absolute;
    top: -9px;
    left: 4px;
    background-color: #ffffff;
    padding: 0 4px;
}

In order to fetch records from the Contact Object, we are using Apex method. Apex method can be called from Lightning Web Components in two ways. Using @Wire Decorator, or by creating Apex Imperative method. In this LWC, we are going to use Apex Imperative Method. An  Apex Imperative method must be a static method annotated with @AuraEnabled.

public with sharing class ContactSearchController {

    @AuraEnabled(cacheable=true)
    public static List<Contact> findContacts(String searchKey) {
        system.debug('searchKey is:'+ searchKey);
        String key = '%' + searchKey + '%';
        List<Contact> lstContacts = new List<Contact>();
        lstContacts = [SELECT Id, Name, Title, Phone, Email FROM Contact WHERE Name LIKE :key LIMIT 10];
        system.debug('lstContacts are:'+ lstContacts);
        return lstContacts;
    }

Now we are done with development of the Lightning Web Component. But it is now available only in our local copy, i.e. the project folder we have selected while creating the Project. To be able to use it, the component must be available in our Salesforce environment, and for that we would need to push all our new components i.e. the LWC and the apex class to Salesforce. Lets now see how it is done:

Push to a Scratch Org

  1. Open Visual Studio, press Command + Shift + P on a Mac or Ctrl + Shift + P on Windows.
  2. Type SFDX and Select SFDX: Push Source to Default Scratch Org.

Verifying and Using the searchContacts LWC

Go back to the prep-release Salesforce org. Go to set up, enter “Lightning Components” in the Quick find box and select. The Lightning Web Components are listed in “Lightning Components” and the type is “LWC”. Verify your lightning component in the list of components.

Now that we have verified our lightening component, let see how does it look like. To use this we will be creating a lightning page. Steps below:

  • Switch the view to Lightning Experience
  • Go to Setup and enter “Lightning App Builder” in Search.
  • Select New, and select “App Page”, give the page name “searchContacts”
  • Select the desired layout. The “contactSearch” component will be available in the custom components section.
  • Drag the “contactSearch” component to a block and activate the page and save it.
  • Open apps menu, and select “searchContacts” and Voila you have your app right there build on your new LWC
  • Enter the search keyword, the contact name and click on “Load Contacts” to get the results on your app

The project is available in github. Follow the link https://github.com/Milanjenasfdc/LightningWebComponents

There we are!!!! We have just created and used our first LWC. We hope this blog helped you understanding the concepts of scratch org, VS set up and LWC. Post your questions feedback on the comments section.

Next blog will be on the Winter 19 Release notes highlights. Stay Tuned 🙂

1 thought on “Lightning Web Components (lwc)”

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.