Handle User Actions in JavaScript
Learning Objectives
After completing this unit, you’ll be able to:
- Create an SFDX project.
- Create a Lightning web component.
- Apply architecture and coding concepts.
In Visualforce, to perform a UI change, sometimes you need to rerender a page on the server. As you learned, with the Lightning Web Components architecture, rerendering happens on the client. You learned how to set properties in JavaScript to change component state, causing the Lightning Web Components engine to rerender the component. You also learned how to respond to user interactions in JavaScript. Let’s observe these concepts in action. Consider this example Visualforce page.
accountSearch.page
<apex:page controller="AccountSearchController" docType="html-5.0"> <apex:form> <apex:input type="number" label="Number of Employees" value="{!numberOfEmployees}"/> <apex:commandButton value="Reset" action="{!reset}"/> </apex:form> </apex:page>
AccountSearchController.cls
public class AccountSearchController { public Integer numberOfEmployees {get; set;} public void reset() { this.numberOfEmployees = null; } }
The reset button clears the input value and the page rerenders on the server. In a Lightning web component, you can make the same UI change using JavaScript alone, like this:
accountSearch.html
<template> <lightning-card> <lightning-input type="number" label="Number of Employees" value={numberOfEmployees} onchange={handleChange}> </lightning-input> <lightning-button label="Reset" onclick={reset}> </lightning-button> </lightning-card> </template>
accountSearch.js
import { LightningElement } from 'lwc'; export default class AccountSearch extends LightningElement { numberOfEmployees = null; handleChange(event) { this.numberOfEmployees = event.detail.value; } reset() { this.numberOfEmployees = null; } }
Code highlights:
accountSearch.html
- Lines 3–8: We use a
lightning-input
component to receive user input.
- Line 6: We bind the
numberOfEmployees
JavaScript property to thelightning-input
component'svalue
attribute.
- Line 7: We bind the
handleChange
method to thelightning-input
component'schange
event.
- Lines 9–12: We define a
lightning-button
base component.
- Line 11: When a user clicks the button, the Lightning Web Components engine invokes the
reset
method.
accountSearch.js
- Line 5: The
handleChange
method reads thelightning-input
component'schange
event, gets the value entered by the user, and stores it in thenumberOfEmployees
property.
- Lines 7–9: The
reset
method empties thenumberOfEmployees
property. Normally we follow the handleEventName convention for naming event handlers, but we’ve usedreset
here to emphasize its similarity to our Apex controller reset method.
Passing a different value
to lightning-input
causes the component to rerender. The difference with the Visualforce implementation is that the rerendering happens on the client, avoiding an additional call to the server.
Respond to User Interactions
Now that we’ve explored some of the differences between Lightning Web Components and the Visualforce development you’re familiar with, let’s work through an example.
Before You Begin
Visualforce developers are very comfortable working in the Developer Console. The programming model for Lightning Web Components, however, requires a different set of developer tools called Salesforce DX (Developer Experience). It includes the Salesforce Command Line Interface (CLI) and Visual Studio Code, which, with the Salesforce Extension Pack, is the recommended code editor for developing on the Salesforce Platform. The Salesforce DX environment was designed to:
- Streamline the entire development lifecycle
- Facilitate automated testing
- Support continuous integration
- Make the release cycle more agile and efficient
Before you start this module’s hands-on activities and hands-on challenges, make sure you complete Quick Start: Lightning Web Components. The first two steps of that badge walk through setting up your Salesforce DX development environment.
Create a New Trailhead Playground
For this project, you need to create a new Trailhead Playground. Scroll to the bottom of this page, click the down arrow next to Launch, and select Create a Trailhead Playground. It typically takes 3–4 minutes to create a new Trailhead Playground.
Note: Yes, we really mean a brand-new Trailhead playground! If you use an existing org or playground, you can run into problems completing the challenges.
Get Your Trailhead Playground Username and Password
Go to your Trailhead Playground. (If it’s not already open, scroll to the bottom of this page and click Launch.) If you see a tab in your org labeled Get Your Login Credentials, great! Skip ahead to step 1.
Otherwise, from the App Launcher (), find and open Playground Starter and follow the steps. If you don’t see the Playground Starter app, check out Find the Username and Password for Your Trailhead Playground on Salesforce Help.
- Click the Get Your Login Credentials tab and take note of your username.
- Click Reset My Password. This sends an email to the address associated with your username.
- Click the link in the email.
- Enter a new password, confirm it, and click Change Password.
Ready to get hands-on? Let’s go.
In this exercise, you create a Lightning web component that rerenders in response to user interactions.
- Create a new project:
- Open Visual Studio Code.
- Open the command palette: Click View | Command Palette.
- In the command palette, select SFDX: Create Project. (If you don’t see it in the list, type
SFDX: Create Project
and then press Enter.)
- Accept the standard template.
- For the project name, enter
lwcForVisualforceDevs
and then press Enter.
- Select a location for the new project and then click Create Project.
- Authorize your Trailhead Playground:
- In the command palette, select (or enter) SFDX: Authorize an Org.
- Select Production: login.salesforce.com.
- For the alias, enter
lwc_for_vf_devs
and then press Enter.
- Use your Trailhead Playground username and password to log in.
- When you are logged in to your Trailhead Playground, leave it open and return to Visual Studio Code.
- In Visual Studio Code, open a terminal window: Click Terminal | New Terminal.
- Create a Lightning web component:
- In the Explorer pane, expand force-app/main/default.
- Right-click the lwc folder and select SFDX: Create Lightning Web Component.
- For the component name, enter
accountSearch
and then press Enter.
- Press Enter again to accept the default directory.
- Replace the contents of your accountSearch.html file with this code:
<template> <lightning-card> <lightning-input type="number" label="Number of Employees" value={numberOfEmployees} onchange={handleChange}> </lightning-input> <lightning-button label="Reset" onclick={reset}> </lightning-button> </lightning-card> </template>
- Replace the contents of your accountSearch.js file with this code:
import { LightningElement } from 'lwc'; export default class AccountSearch extends LightningElement { numberOfEmployees = null; handleChange(event) { this.numberOfEmployees = event.detail.value; } reset() { this.numberOfEmployees = null; } }
- To make this component available on app pages in an org, replace the contents of your accountSearch.js-meta.xml file with this code:
<?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> </targets> </LightningComponentBundle>
- Save the three files you edited: accountSearch.html, accountSearch.js, and accountSearch.js-meta.xml.
- Deploy the project files to your Trailhead Playground: Right-click the lwc folder and select SFDX: Deploy Source to Org.
- If your Trailhead Playground isn’t already open, open it. (In the command palette, select (or enter) SFDX: Open Default Org.)
- In your Trailhead Playground, click and then click Setup.
- In the Quick Find box, enter
Lightning App Builder
and then select Lightning App Builder.
- Create a new Lightning page:
- Click New.
- Choose App Page and click Next.
- For the label, enter
LWC Visualforce Devs
, and then click Next.
- For the layout, choose Header and Left Sidebar.
- Click Done.
- Drag the accountSearch component to the page sidebar.
- Save the page.
- Activate the page:
- Click Activate.
- Keep the default app name (LWC Visualforce Devs) and click Save.
- When prompted to add the page to the navigation menu, click Finish.
- Exit the Lightning App Builder.
- Open the new page: In the App Launcher search, enter
lwc
, and then under Items, select LWC Visualforce Devs.
- Enter a value in the input field, and then click the Reset button.
The JavaScript code you implemented should clear the input field and cause the Lightning Web Components engine to rerender the component.
Look at that! You created a Lightning web component and added it to a page in your org. Now try your hand at another one in the hands-on challenge.
Resources