Lightning Web Components Basics

Discover Lightning Web Components

Explain the Lightning Web Components programming model. List the benefits of using Lightning web components. Find what you need to get started developing Lightning web components.
  • Programming with Web Standards - standard technologies like HTML, JavaScript, and CSS are used to build the next generation of Salesforce apps while maintaining compatibility with existing Aura components.
    • LWC opens to door to existing technologies
  • Why Lightning Web Components?
    • Modern browsers are based on web standards that are constantly improving what browsers can present to a user
    • Since LWC is build on code that runs natively in browsers, LWC is lightweight and performant
    • Its easier to find solutions to common places on the web, find developers with necessary skills/experience, develop faster, use full encapsulation so components are more versatile
    • Browsers have been creating web components for years: select, video, input - any tags that serve as more than a container
  • Simple Component Creation
    • Simply create components using HTML, JavaScript, and (optionally) CSS:
      • HTML: Provides structure for your component
      • JavaScript: Defines the core business logic and event handling
      • CSS: Provides the look, feel, and animation for your component
    • At a minimum, you just need an HTML file and a Javascript file with the same name in the same folder with the same name
      • Deploy those to an org with some metadata and Salesforce compiles the files and takes care of the component construction automatically

HTML

  • template tag is a fundamental building block of component’s HMTL - it allows you to store pieces of HTML
<template>
    <input value={message}></input>
</template>

JavaScript

  • Import statements and class declarations covered below.
import { LightningElement } from 'lwc';
export default class App extends LightningElement {
  message = 'Hello World';
}

CSS

  • At a minimum only HTML and JavaScript files are needed
input {
   color: blue;
}

https://webcomponents.dev/create/lwc

  • The header is a link that lets us try out components, change them, and see immediate results
    • You can use GitHub to log in to WebComponents.dev
    • “Stories” tab at webcomponents.dev shows the output

  • Lightning Web Components and Aura Components Do Work Together
    • Over time, Aura components are likely to migrate to the Lightning Web Component model, but in the meantime both are supported.
    • Aura components can contain Lightning web components, but not vice versa
    • A pure Lightning web components implementation provides full encapsulation and evolving adherence to common standards

  • References and Resources
    • Salesforce DX tool set
      • Scratch Orgs: disposable Salesforce orgs to support development and testing
      • Dev Hubs: feature that manages scratch orgs
      • Salesforce Command Line Interface (CLI): provides a quick way to run operations for creating and configuring scratch orgs and deploying components
      • Lightning Component Library:
    • GitHub: extensions, samples, etc are available through GitHub repos
      • Visual Studio Code Salesforce Extension Pack: provides code-hinting, lint warnings, built-in commands
      • LWC Recipes: provides a GitHub repo to help you see how web components work
      • E-Bikes Demo: end-to-end implementation of Lightning web components to create an app. Can deploy in your own Trailhead Playground
      • Lightning Data Service (LDS): access data and metadata from Salesforce. Base Lightning components that work with data are built on LDS
      • Lightning Locker: Lightning Locker secures components from one namespace from components in another namespace

  • A Lightning web component requires the following files: HTML, JS
  • An IDE, like WebComponents.dev, lets you: try your component files in a simulated environment

    The following images were taken from a Salesforce blog post introducing LWCs located here.

2014 web stack

2019 web stack

Lightning Web Components

Lightning Web Components versus Aura Components

Create Lightning Web Components

Describe the contents of each component file. Create JavaScript methods for a Lightning web component. Use Lifecycle Hooks in component JavaScript.
  • A component simply needs a folder and its file with the same name - they’re auto-linked by name and location

  • productCard Component in eBikes Sample Repo
    • Linked above an example of a data display element - the following breaks down the structure of the files that form the LWC
    • All LWCs have a namespace that’s separated from the folder name by a hyphen. Ex: markup for the LWC component with the folder name app in the default namespace c is <c-app>
    • But, Salesforce platform doesn’t allow hyphens in the component folder or file names, so mycomponent cannot be named my-component. Instead, we use camel case to name it myComponent
      • camelCase component folder names map to kebab-case in markup.
      • In markup, to reference aa component with folder name myComponent, use <c-my-component>
  • Example 1: HTML/Javascript Files
    • Lightning web component HTML files all include the template tag - these contain the HTML that defines the structure of your component
    • View examples below by copying/pasting into the appropriate files at webcomponents.dev/create/lwc
    • Identifiers in the curly brace {} are bound to the fields of the same name in correspondning JavaScript class

HTML File

<template>
    <div>
        <div>Name: {name}</div>
        <div>Description: {description}</div>
        <div>Category: {category}</div>
        <div>Material: {material}</div>
        <div>Price: {price}</div>
        <div><img src={pictureUrl}/></div>
    </div>
</template>

JavaScript File

import { LightningElement } from 'lwc';
export default class App extends LightningElement {
   name = 'Electra X4';
   description = 'A sweet bike built for comfort.';
   category = 'Mountain';
   material = 'Steel';
   price = '$2,700';
   pictureUrl = 'https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/electrax4.jpg';
}

  • Example 2: HTML/Javascript Files
    • Real world example - you want to display data, but it can take time to load. Can use conditional directives within the template to determine which visual elements are rendered.

HTML File

<template>
    <div id="waiting" if:false={ready}>Loading…</div>
    <div id="display" if:true={ready}>
        <div>Name: {name}</div>
        <div>Description: {description}</div>
        <div>Category: {category}</div>
        <div>Material: {material}</div>
        <div>Price: {price}</div>
        <div><img src={pictureUrl}/></div>
    </div>
</template>

JavaScript File

import { LightningElement } from 'lwc';
export default class App extends LightningElement {
   name = 'Electra X4';
   description = 'A sweet bike built for comfort.';
   category = 'Mountain';
   material = 'Steel';
   price = '$2,700';
   pictureUrl = 'https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/electrax4.jpg';
   ready = false;
   connectedCallback() {
       setTimeout(() => {
           this.ready = true;
       }, 3000);
   }
}

  • Base Lightning Web Components
    • Generally you don’t want to build all your components ground up - instead you can use a base Lightning web component.
      • Example components: field types, display controllers, navigation items, etc
    • Replace the div tags for material and category with a lightning-badge component:
<template>
    <div id="waiting" if:false={ready}>Loading…</div>
    <div id="display" if:true={ready}>
        <div>Name: {name}</div>
        <div>Description: {description}</div>
        <lightning-badge label={material}></lightning-badge>
        <lightning-badge label={category}></lightning-badge>
        <div>Price: {price}</div>
        <div><img src={pictureUrl}/></div>
    </div>
</template>
  • Working with JavaScript
    • JavaScript methods define what to do with input, data, events, changes to state, etc, to make your component work
    • export statement below defines a class that extends the LightningElement class
    • JavaScript file must included at least the following code, where MyComponent is the name you assign the component class
import { LightningElement } from 'lwc';
export default class MyComponent extends LightningElement {
}
  • The LWC Module
    • Lightning Web Components uses modules to build functionality and make it accessible to JavaScript in your component file.
      • Core module is lwc
      • LightningElement is bbase class for LWCs, which allows us to use connectedCallback()
      • connectedCallback() is a “lifecycle hook.” This method is triggered when a component is inserted in the document object model (DOM).
// import module elements
import { LightningElement} from 'lwc';
// declare class to expose the component
export default class App extends LightningElement {
    ready = false;
    // use lifecycle hook
    connectedCallback() {
        setTimeout(() => {
            this.ready = true;
        }, 3000);
    }
}
  • Lifecycle Hooks provide a means of “hooking” your code up to critical events in a component’s lifecycle.
    • Component lifecycle includes when a component is:
      • Created
      • Added to the DOM - connectedCallback()
      • Rendered in the browser
      • Encountering errors
      • Removed from the DOM - disconnectedCallback()
    • Note that the this keyword was used - it refers to the top level of the current context. Above, this context is the class.
  • Decorators - used in JavaScript to modify the behavior of a property/function
    • Need to be imported from the lwc module. Examples:
      • @api: marks a field/property as public. Public properties are reactive - the framework observes the property for changes.
      • @track: tells the framework to observe changes to properties of an object or elements of an array.
      • @wire: gives you an easy way to get and bind data from a Salesforce org.
import { LightningElement, api } from 'lwc';
export default class MyComponent extends LightningElement{
    @api message;
}
  • Example 3: HTML/JavaScript with Decorators
    • Following example uses the @api decorator to render a value from one component (bike) in another component (app)

“App” component HTML

<!-- app.html -->
<template>
<div>
    <c-bike bike={bike}></c-bike>
</div>
</template>

“App” component JavaScript

// app.js
import { LightningElement } from 'lwc';
export default class App extends LightningElement {
    bike = {
        name: 'Electra X4',
        picture: 'https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/electrax4.jpg'
    };
}

“Bike” component HTML

<!-- bike.html -->
<template>
    <img src={bike.picture} alt="bike picture" />
    <p>{bike.name}</p>
</template>

“Bike” component JavaScript

// bike.js
import { LightningElement, api } from 'lwc';
export default class Bike extends LightningElement {
    @api bike;
}

Deploy Lightning Web Component Files

Configure Lightning web component files for display in an org. Deploy your files to an org. Verify component behavior in an org environment.
  • Steps to Create an LWC
    1. Create a project via SFDX: Create Project from VS Code
    2. Right-click the lwc folder and select SFDX: Create Lightning Web Component
    3. For this example, name the component LWC, and accept the default location
    4. Connect Visual Studio to Trailhead by authorizing an org with command SFDX: Authorize an Org in Visual Studio
    5. Edit the boilerplate bikeCard.html, bikeCard.js, and bikeCard.js-meta.xml files with the following:

bikeCard.html

<template>
    <div>
        <div>Name: {name}</div>
        <div>Description: {description}</div>
        <lightning-badge label={material}></lightning-badge>
        <lightning-badge label={category}></lightning-badge>
        <div>Price: {price}</div>
        <div><img src={pictureUrl}/></div>
    </div>
</template>

bikeCard.js

import { LightningElement } from 'lwc';
export default class BikeCard extends LightningElement {
   name = 'Electra X4';
   description = 'A sweet bike built for comfort.';
   category = 'Mountain';
   material = 'Steel';
   price = '$2,700';
   pictureUrl = 'https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/electrax4.jpg';
 }

bikeCard.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <!-- The apiVersion may need to be increased for the current release -->
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>Product Card</masterLabel>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

The Component Configuration File

  • js-meta.xml file - provides metadata for Salesforce, including the design configuration for components intended for use in Lightning App Builder
    • apiVersion is required, and binds the component to a Salesforce API version
    • isExposed (true or false) is optional, makes the component available from other namespaces
    • targets is optional, and specifies behavior to each type of Lightning page
    • Reference these documents for full list of syntax

Example from ebikes repo:

<?xml version="1.0" encoding="UTF-8" ?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>Product Card</masterLabel>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
        <target>lightningCommunity__Page</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <objects>
                <object>Product__c</object>
            </objects>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

Displaying a Component in an Org

  • 2 options for displaying a component:
    1. Set the component to support flexipage types (home, record home, etc)
    2. Create a tab pointing to an Aura component containing the LWC

Deploy Your Files

  • Authenticate with your Dev Hub org using SFDX: Authorize an Org
  • Deploy the project files using SFDX: Deploy this Source to Org

Create a New Page for Your Component

  • Setup > Quick Find > Lightning App Builder > New > App Page > One Region
  • Drag the component “Product Card” onto the page

Handle Events in Lightning Web Components

Create an app that includes multiple components. Describe the file structure of a complex component. Handle events.
  • Follow an Event’s Journey
    • Sample app discussed below has four components working together:
      1. Tile: displays an individual item
      2. List: arranges the tiles
      3. Detail: displays item details when clicked
      4. Selector: contains the whole set of components
  • Component Composition & Relationships
    • Several zipped up files and folders are provided on the trailhead, shown below (data, detail, list, selector, tile)

  • Events Up, Properties Down
    • Multiple components work together in this app - some are nested within each other. LWCs, which are custom HTML elements, nest inside one another just like HTML elements

  • Passing Information Up
  • Passing Information Down
  • Handling Events in HTML
  • Selector App Event Pattern
  • Deploy Your Files to Your Org

Add Styles and Data to a Lightning Web Component

Use CSS and Lightning Design System with a component. Get data from a Salesforce org. Deploy your app to an org and test it.