Start tracking your progress
Trailhead Home
Trailhead Home

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="InputController" 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 the lightning-input component's value attribute.
  • Line 7: We bind the handleChange method to the lightning-input component's change 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 the lightning-input component's change event, gets the value entered by the user, and stores it in the numberOfEmployees property.
  • Lines 7–9: The reset method empties the numberOfEmployees property. Normally we follow the handleEventName convention for naming event handlers, but we’ve used reset 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 (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 Trailhead Help.

  1. Click the Get Your Login Credentials tab and take note of your username.
  2. Click Reset My Password. This sends an email to the address associated with your username.
  3. Click the link in the email.
  4. 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.

  1. Create a new project:
    1. Open Visual Studio Code.
    2. Open the command palette: Click View | Command Palette.
    3. 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.)
    4. Accept the standard template.
    5. For the project name, enter lwcForVisualforceDevs and then press Enter.
    6. Select a location for the new project and then click Create Project.
  2. Authorize your Trailhead Playground:
    1. In the command palette, select (or enter) SFDX: Authorize an Org.
    2. Select Production: login.salesforce.com.
    3. For the alias, enter lwc_for_vf_devs and then press Enter.
    4. Use your Trailhead Playground username and password to log in.
    5. When you are logged in to your Trailhead Playground, leave it open and return to Visual Studio Code.
  3. In Visual Studio Code, open a terminal window: Click Terminal | New Terminal.
  4. In the terminal, set your Trailhead Playground as the default for this project: Enter this command and then press Enter:
  5. sfdx force:config:set defaultusername=lwc_for_vf_devs
    
  6. Create a Lightning web component:
    1. In the Explorer pane, expand force-app/main/default.
    2. Right-click the lwc folder and select SFDX: Create Lightning Web Component.
    3. For the component name, enter accountSearch and then press Enter.
    4. Press Enter again to accept the default directory.
  7. Replace the contents of your accountSearch.html file with this code:
  8. <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>
  9. Replace the contents of your accountSearch.js file with this code:
  10. import { LightningElement } from 'lwc';
    export default class AccountSearch extends LightningElement {
        numberOfEmployees = null;
        handleChange(event) {
            this.numberOfEmployees = event.detail.value;
        }
        reset() {
            this.numberOfEmployees = null;
        }
    }
  11. To make this component available on app pages in an org, replace the contents of your accountCreator.js-meta.xml file with this code:
  12. <?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>
  13. Save the three files you edited: accountSearch.html, accountSearch.js, and accountSearch.js-meta.xml.
  14. Deploy the project files to your Trailhead Playground: Right-click the lwc folder and select SFDX: Deploy Source to Org.
  15. If your Trailhead Playground isn’t already open, open it. (In the command palette, select (or enter) SFDX: Open Default Org.)
  16. In your Trailhead Playground, click Setup and then click Setup.
  17. In the Quick Find box, enter Lightning App Builder and then select Lightning App Builder.
  18. Create a new Lightning page:
    1. Click New.
    2. Choose App Page and click Next.
    3. For the label, enter LWC Visualforce Devs, and then click Next.
    4. For the layout, choose Header and Left Sidebar.
    5. Click Finish.
  19. Drag the accountSearch component to the page sidebar.
  20. Save the page.
  21. Activate the page:
    1. Click Activate.
    2. Keep the default app name (LWC Visualforce Devs) and click Save.
    3. When prompted to add the page to the navigation menu, click Finish.
  22. Exit the Lightning App Builder.
  23. Open the new page: In the App Launcher search, enter lwc, and then under Items, select LWC Visualforce Devs.
  24. 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