Lightning Web Components in Lightning Communities

As part of Salesforce’s Spring ‘19 release, we were introduced to Lightning Web Components (LWC). Lightning Web Components is a new programming model developers can use to build Lightning components on the Salesforce Platform. Lightning Web Components has a modern and fast tech stack, which boosts developer productivity when building components. Lightning Web Components can integrate with Lightning Data Service and Salesforce APIs with very minimal boilerplate code. Even better, you can start using Lightning Web Components in Lightning Communities today!

You can have both custom Aura components and custom Lightning Web Components within the same Lightning community. Additionally, Lightning Web Components respect the Content Security Policy set by the community. For more info around CSP in Communities, check out this blog.

Why use Lightning Web Components

You are probably asking yourself why you or your business should start using Lightning Web Components? Lightning Web Components was built with two main goals in mind:

  1. Improve developer experience
  2. Increase performance

These are huge wins for both businesses and developers. With the improved performance of Lightning Web Components and the increased developer productivity, it means quicker deployment of new features and happier customers.

Let’s dive into the advantages of Lightning Web Components:

  • Modern JavaScript
    • With ES6+ support of JavaScript, use all your favorite features of ES6+. For a full list of JavaScript support, see the Salesforce Developer Guide.
    • “Wait does that mean I can use arrow functions, classes, spread operator, and deconstruction?” YEP! 😎
  • Increased performance
    • Lightning Web Components was built on top of web standards like Web Components, Custom Elements, and more. This means that much of Lightning Web Components is natively supported by the browser (Polyfills and transpilation are used for browsers that don’t support some of the web standards). In return, there are no more heavy framework abstractions that slow down applications.
    • With significantly less framework code, less time is needed to download the framework.
    • Lightning Web Components also utilizes a smart virtual DOM, which allows it to intelligently update specific components only when changes are needed.
  • Integrates easily with Lightning Data Service (LDS) and Salesforce APIs
    • Lightning Data Service allows components to interact with Salesforce data without having to worry about performant boilerplate code.
    • Because of how Lightning Web Components is built, the Lightning Data Service boilerplate is kept in the JavaScript file. This makes the HTML file simpler and easier to read, as only DOM elements are kept in the HTML file.
  • Modern testing and tooling
    • You can use Jest to test Lightning Web Components! Jest enables you to write powerful unit tests with ease.
    • Lightning Web Components has its own Visual Studio Code Extension that provides powerful autocomplete, linting, and more.
  • Learn once, apply everywhere
    • Because Lightning Web Components leverages modern web standards, you learn skills that are transferable across the JavaScript web world when you learn how to write in Lightning Web Components.

For a high-level overview of how Lightning Web Components was built, check out this blog.

How to create a Lightning web component in Communities

In this section, we will go over how to create a simple button with Lightning Web Components that displays text coming from what the admin inputs in the Community Builder Property Editor. Thus, the final result will have a button in your Community with configurable text via the Community Builder Property Editor.

 

Tip: We recommend using Visual Studio Code with the Salesforce DX Visual Studio Code extension. However, the steps below will be editor agnostic (sfdx commands in the terminal).

Step 1: Set up your Environment

Follow the first module outlined in Quick Start: Lightning Web Components

Step 2: Create an empty Salesforce DX project

If you want to use an existing project such as your own project or a sample, you can skip this step. Otherwise, input these commands into your terminal:

$ cd {into_directory_you_want_to_create_project}
$ sfdx force:project:create –projectname sample_project

Step 3: Authorize your org

If your org is on a My Domain subdomain, modify the sfdcLoginUrl in sfdx-project.json to your My Domain login URL before authorizing your org. For more details, check out the Salesforce DX Developer Guide.

$ cd sample_project
$ sfdx force:auth:web:login –setdefaultdevhubusername –setalias my-hub-org

Enter your org credentials in the opened browser window. After logging in, click “Allow”.

Step 4: Create a scratch org

$ sfdx force:org:create -s -f config/project-scratch-def.json -a sample_project –setdefaultusername

-a sample_project specifies the alias to your scratch org. Feel free to put your own alias.

Step 5: Create a Lightning Web Component

$ cd {app_dir}/main/default/lwc
$ sfdx force:lightning:component:create –type lwc -n myLightningWebComponent

app_dir is probably force-app, unless you changed the name.

A directory called myLightningWebComponent will be created in the lwc folder. Inside the directory, there will be three files: JavaScript, HTML, and XML.

Step 6: Build a simple button

The button will have configurable text from the Community Builder Property Editor and log a message when clicked on.

Open the JavaScript file (myLightningWebComponent.js). You should see a class called MyLightningComponent. It extends LightningElement. This will let the Lightning Web Components framework know that this class is a Lightning web component.

We want to display the button text dynamically based on input from the Community Builder Property Editor. At the component level, we will need a property to bind to the HTML, so that every time the property changes, the HTML is updated.

Create a property called buttonText in the class to control text of the button.

export default class MyLightningWebComponent extends LightningElement {
 buttonText;
}

Import api from the lwc module and add @api in front of the property. This makes the property to be settable from the outside, such as a parent component or in our case the Community Builder Property Editor.

import { LightningElement, api } from 'lwc';
export default class MyLightningWebComponent extends LightningElement {
 @api buttonText;
}

For more documentation on @api, check out Public Properties in the Salesforce Developer Guide.

Add a click handler in the class for when the button gets clicked on.

handleClick() {
 console.log("Button Clicked!");
}

Your final JavaScript file should look similar to this:

 import { LightningElement, api } from 'lwc';
  
export default class MyLightningWebComponent extends LightningElement {
 @api buttonText;

 handleClick() {
   console.log("Button Clicked!");
 }
}

Then open the HTML file (myLightningWebComponent.html). We want to display a button with text rendered from the property in our JavaScript file. We also want to bind the click event of the button to our custom handler. To do both of these, we can use curly braces.

<template>
    <button onclick={handleClick}>{buttonText}</button>
</template>

Step 7: Add custom CSS to your component

To do this, we’ll create a new .css file in the same directory as your component with the same name as the other files.

$ touch myLightningWebComponent.css

Open the file and add some CSS properties to the component:

button {
 color: black;
 background-color: aqua;
 text-align: center;
 border: none;
 font-size: 14px;
 border-radius: 10px;
 padding: 5px 50px 5px 50px;
}

Notice how simple our CSS selector is. With the benefit of the Shadow DOM, we don’t need obscure, complicated CSS selectors because we know that this CSS will be self-contained in this component.

If you want to use CSS variables from Aura design tokens or Communities standard design tokens, use the syntax laid out in the Salesforce Developer Guide.

Step 8: Allow your component to appear in the Community Builder

Open your <component>.js-meta.xml file, (ex. myLightningWebComponent.js-meta.xml) and
set isExposed to true. This will expose the component in all orgs and in Lightning App Builder and Community Builder.

Add the targets field in the LightningComponentBundle root with lightningCommunity__Page as a target.

 
<targets>
    <target>lightningCommunity__Page</target>
</targets>

Targets define what type of page you want your component to be added to. lightningCommunity__Page allows the component to be shown on a Community Page. Without this tag, your component would not appear in the Community Builder. For all supported tags, look at Configuration File Tags in the Salesforce Developer Guide.

Specify what properties the Community Builder can set. First, add another target called lightningCommunity__Default in .js-meta.xml file.

Below the targets, add the following:

<targetConfigs>
    <targetConfig targets="lightningCommunity__Default">
        <property name="buttonText" type="String" default="defaultText" />
    </targetConfig>
</targetConfigs>

Inside targetConfig, we can configure what the Community Builder Property Editor can set in the component. For our component, you’ll notice we added the text of the button to be set by the Community Builder Property Editor.

Note: The property name must match the name of the @api property in the JavaScript file. For specifications of property fields, see the Configuration File Tags in the Salesforce Developer Guide.

Add a masterLabel, if you want to have a specified name for your component in the Community Builder.

Your final .js-meta.xml file should look similar to this:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="myLightningWebComponent">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>My Lightning Web Component</masterLabel>
    <targets>
      <target>lightningCommunity__Page</target>
      <target>lightningCommunity__Default</target>
    </targets>
    <targetConfigs>
      <targetConfig targets="lightningCommunity__Default">
          <property name="buttonText" type="String" default="defaultText" />
      </targetConfig>
    </targetConfigs>
<LightningComponentBundle>

Step 9 (optional): Add an icon for the Community Builder component palette

If you want an icon other than the default to appear next to your component in the Community Builder component palette, add your own SVG file titled the same name as the other files (ex. myLightningWebComponent.svg).

Step 10: Push the changes to the scratch org and open the scratch org

$ sfdx force:source:push
$ sfdx force:org:open

 

Step 11: Create a community

If you are new to Communities, check out this help article or this Trailhead module to learn how to create a community in Salesforce.

Step 12: Drag and drop your component into the community!

 

Using Lightning Web Components with other components

Lightning Web Components can coexist on a page in Communities with an Aura component. You can also create an Aura component that includes Lightning Web Components. However, you can not create a Lightning web component that includes Aura Components. Check out the Salesforce Developer Guide if you want to know how to add a Lightning web component inside an Aura component.

To communicate between parent and child Lightning Web Components, use custom events that are built from standard DOM Events supported in each browser. If you need to communicate between components that aren’t in the same component hierarchy, you can use a publish-subscribe module.

To fire standard Aura events from Lightning Web Components, such as for page navigation, please consult the table listed in section Migrate Standard Aura Events.

Samples and more advanced examples

To help kick-start your development with Lightning Web Components, you can check out the samples on the Trailhead Sample Gallery. I have also built a Community-specific sample featuring examples of Lightning Web Components in Communities. Some important callouts in the components in the sample:

For all Lightning Web Components specific documentation, head over to the Salesforce Developer Guide (Which is likely already in your bookmarks by now). For more practice and guided steps, check out all the Lightning Web Components modules on Trailhead.

Lightning Web Components is a revolutionary programming model for Salesforce. Let the innovation begin 🌟. Thanks for reading this blog and feel free to ask any questions you have in the comments here!

Resources

About the authors

Kenan Mesic is a full stack Software Engineer on Community Cloud at Salesforce. He is a JavaScript guru and has experience in multiple JavaScript frameworks. Feel free to connect with him on Twitter at @dev__ken.

Haris Ikram is a Senior Director of Product Management on Community Cloud.

Ronak Shah is an Engineering Manager on Community Cloud.

Leave your comments...

Lightning Web Components in Lightning Communities