進行状況の追跡を始めよう
Trailhead のホーム
Trailhead のホーム

Create Lightning Web Components

Learning Objectives

After completing this unit, you’ll be able to:
  • Describe the contents of each component file.
  • Create JavaScript methods for a Lightning web component.
  • Use Lifecycle Hooks in component JavaScript.

Some Serious Play Time

Say you want to build a data display element, independent of a specific object in Salesforce. A good example is the productCard component in the ebikes sample repo. Let’s examine that card component, and build our own version from scratch so you can see how it evolves into a full-fledged Lightning web component. You’ll quickly get the basics when you build up the parts of a component in the Lightning Web Components Playground and explore more samples.

A component simply needs a folder and its files with the same name. They’re automatically linked by name and location.

Component files in a folder

All Lightning web components have a namespace that’s separated from the folder name by a hyphen. For example, the markup for the Lightning web component with the folder name app in the default namespace c is <c-app>. You can see this in main.js in the Lightning Web Components Playground.

However, the Salesforce platform doesn’t allow hyphens in the component folder or file names. What if a component’s name has more than one word, like “mycomponent”? You can’t name the folder and files my-component, but we do have a handy solution.

Use camel case to name your component myComponent. Camel case component folder names map to kebab-case in markup. In markup, to reference a component with the folder name myComponent, use <c-my-component>.

For example, the LWC Samples repo has the viewSource folder containing the files for the viewSource component. When the hello component references the viewSource component in HTML, it uses c-view-source.

A Look Into the HTML File

Lightning web component HTML files all include the template tag. The template tag contains the HTML that defines the structure of your component. Let’s look at the HTML for a simplified version of the productCard component from the ebikes repo.

Follow along by pasting these examples in the Lightning Web Components Playground. Paste this into app.html (replacing any existing HTML in the 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>

The identifiers in the curly braces {} are bound to the properties of the same name in the corresponding JavaScript class.

Here’s a JavaScript file to support this HTML. Paste this into app.js.
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';
}

Click Run to see the bike and details.

Now let’s say you want to display data, but you know it can take some time to load. You don’t want the user wondering what’s up. You can use if:false and if:true conditional directives within your template to determine which visual elements are rendered.

The content in the “display” div tag doesn’t appear until the value of ready is true in the 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>

Here’s some JavaScript to test it in the playground. This holds our data values and sets a 3-second timer. After 3 seconds, the content should appear. (Of course, this is only for testing purposes.)

import { LightningElement, track } 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';
 
   @track
   ready = false;

   connectedCallback() {
       setTimeout(() => {
           this.ready = true;
       }, 3000);
   }
}

Click Run to see the conditional directive working.

Standard Lightning Web Components

Now, you don’t want to build all your components from the ground up. So let’s explore using a base Lightning web component. And of course, there are lots of components, including field types, display controllers, navigation items, and more. All of them are listed in the Component Library.

Let’s make the details of the bike stand out. To do this, replace the div tags for material and category in the last example with a lightning-badge component. Here's the HTML.

<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>

The words Steel and Mountain appear as lightning badges. It’s that simple.

Lightning badges in use

OK. Let’s look at the JavaScript.

Working with JavaScript

Here’s where you make stuff happen. As you’ve seen so far, JavaScript methods define what to do with input, data, events, changes to state, and more to make your component work. Lightning web components use common JavaScript ECMAScript 8 methods and syntax.

The JavaScript file for a Lightning web component must include at least this code, where MyComponent is the name you assign your component class.

import { LightningElement } from 'lwc';
export default class MyComponent extends LightningElement {

}

The export statement defines a class that extends the LightningElement class. As a best practice, the name of the class usually matches the file name of the JavaScript class, but it’s not a requirement.

The LWC Module

The Lightning Web Component model uses modules (built-in modules were introduced in ECMAScript 6) to bundle core functionality and make it accessible to the JavaScript in your component file. The core module for Lightning web components is lwc.

Bring in the module with the import statement and specify the functionality of the module that your component uses.

In our example, the import statement indicates the JavaScript uses the LightningElement and track functionality from the lwc module.

// import module elements
import { LightningElement, track } from 'lwc';

// declare class to expose the component
export default class App extends LightningElement {


// add decorator   
    @track 
    ready = false;


// use lifecycle hook
    connectedCallback() {
        setTimeout(() => {
            this.ready = true;
        }, 3000);
    }
}

These two pieces of imported functionality are quite different.

  • LightningElement is our base class for Lightning web components.
  • track is a decorator. We delve into decorators in the next section.

Decorators

Decorators are often used in JavaScript to extend the behavior of a class, property, getter, setter, or method.

Examples of Lightning Web Component decorators include:

  • @api: Marks a property as public for use in your template or other components.
  • @track: Marks a property for internal monitoring. A template or function using this property forces a component to rerender when the property’s value changes. Use this to store values locally, especially as a user interacts with your component.
  • @wire: Gives you a way to get and bind data. This implementation simplifies getting data from a Salesforce org.

You can import multiple decorators. Like:

import { LightningElement, track, api } from 'lwc';

But, be aware, apply only one Lightning Web Component decorator to a property at a time. For example, a property can’t have @api (public reactive) and @track (private reactive) decorators at the same time.

Use these decorators as a way to extend functionality with short syntax. For example, let’s look at that last JavaScript example again. Try the following with and without the @track decorator to see the behavior. The @track decorator provides value tracking, acting as a listener for changes to a declared variable, with one simple line.

import { LightningElement, track } from 'lwc';
export default class App extends LightningElement {
   
    @track 
    ready = false;

    connectedCallback() {
        setTimeout(() => {
            this.ready = true;
        }, 3000);
    }
}

Component Lifecycle Hooks

The Lightning Web Component model provides methods that allow you to “hook” your code up to critical events in a component’s lifecycle. These events include when a component is:

  • Created
  • Added to the DOM
  • Rendered in the browser
  • Encountering errors
  • Removed from the DOM

Respond to any of these lifecycle events using callback methods. For example, the connectedCallback() is invoked when a component is inserted into the DOM. The disconnectedCallback() is invoked when a component is removed from the DOM.

In the JavaScript file we used to test our conditional rendering, we used the connectedCallback() method to automatically execute code when the component is inserted into the DOM. The code waits 3 seconds, then sets ready to true.

import { LightningElement, track } from 'lwc';
export default class App extends LightningElement {
   
    @track 
    ready = false;

    connectedCallback() {
        setTimeout(() => {
            this.ready = true;
        }, 3000);
    }
}

Notice we used the this keyword. This usage should be familiar if you’ve written JavaScript, and behaves just like it does in other environments. The this keyword in JavaScript refers to the top level of the current context. Here, the context is this class. Which ready? This class’s ready. The connectedCallback() method assigns the value for the top level ready variable. It’s a great example of how the Lightning Web Component model lets you bring JavaScript features into your development. You can find a link to good information about this in the Resources section.

We’re moving fast and you’ve been able to try some things out. In the next unit, we take a step back and talk more about the environment where the components live.

Bonus! Try These Components in the Playground

Now that you’re familiar with the Lightning Web Components Playground, take a little time to experiment with some of the examples in the Lightning Web Components Recipes repo. Try pasting some of the HTML, JavaScript, and CSS from the examples there into the Lightning Web Components Playground as a great way to get familiar with core component concepts.

Resources

retargeting