Skip to main content

Create a Hello World Lightning Web Component

Learning Objectives

In this project, you’ll:

  • Build a set of simple Lightning web components.
  • Retrieve and display data from a single record, and then from a list of records.
  • Encapsulate functionality into child components.
  • Use events for cross-component communication.

Introduction

In this project you experiment with the basic concepts of Lightning Web Components by creating an app that lets park rangers track bears.

Lightning Web Components is the new programming model for building Lightning components. It uses the latest web standards and can interoperate with the original Aura programming model.

In this project you work for Ursus Park, a fictitious national park. The application you create allows rangers to track bears that are wandering in the park.

Overview of completed Ursus Park app

Note

Note

In this project, we develop against a Trailhead Playground org. You can also develop Lightning web components against scratch orgs using the force:source:push command. Learn more about source-driven development with the App Development with Salesforce DX module.

Before You Begin

Before you take on this project, make sure you complete these steps from Quick Start: Lightning Web Components. You won't be able to complete this project if you haven't completed the steps in the Quick Start.

Make sure you’ve installed VS Code as well as the Salesforce CLI.

Setup Your Trailhead Playground

  1. To create a new Trailhead Playground, click the dropdown at the end of this step and select Create a Trailhead Playground. The Create a Trailhead Playground dropdown in a module's hands-on challenge.
  2. Once you have a Trailhead Playground, click Launch.

If you see a tab in your org labeled Get Your Login Credentials, great! Follow the steps below. 

If not, open the App Launcher ( App Launcher), find and select 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.

Set Up the Ursus Park App

  1. Open a command prompt, such as cmd on Windows or Terminal on MacOS.
  2. Clone the Ursus Park app git repository.
    git clone https://github.com/trailheadapps/build-apps-with-lwc.git
    The repository contains the Ursus Park app, a Bear object with a set of fields, record and page layouts, and Apex code that retrieves bear records and sample bear records. This project base helps us focus on the Lightning Web Component development. Note that VS Code has integrated Git support, and you can also install it directly from the open source site here: https://git-scm.com/
  3. Navigate to the new build-apps-with-lwc directory.
    cd build-apps-with-lwc
  4. Authorize your Trailhead Playground with the Salesforce CLI, save it with a bear-trackingalias and set the current user as the default user:
    sf org login web -s -a bear-tracking
  5. When a browser window with the Salesforce login page opens, enter your Trailhead Playground credentials.
  6. Deploy the app code to the org.
    sf project deploy start -d force-app/main/default
  7. Assign the Ursus Park User permission set to the current user.
    sf org assign permset -n Ursus_Park_User
  8. Import the sample data.
    sf data import tree -p data/plan.json
  9. Open the org in a browser.
    sf org open
  10. From the App Launcher ( App Launcher), find and select Ursus Park. This opens the Lightning application.
  11. Click the Bears tab and ensure that it’s populated with some sample data.

Create a Hello World Lightning Web Component with Static HTML

Let’s create our first Lightning web component: a simple hello world component.

  1. Open VS Code.
  2. Add the project folder you just cloned from GitHub by clicking File > Open Folder and navigating to the build-apps-with-lwc folder.
  3. In the sidebar, expand the force-app/main/default folder.
  4. Right-click the force-app/main/default/lwc folder, click SFDX: Create Lightning Web Component and name the component helloWebComponent.
    Alternatively, you can achieve the same result by running sf lightning generate component --type lwc -n helloWebComponent -d force-app/main/default/lwc in a command prompt.
  5. Replace the contents of helloWebComponent.htmlwith the following markup.
    <template>
    	<lightning-card title="Lightning Web Component" icon-name="custom:custom14">
    		<div class="slds-var-m-around_medium">
    			<h2>Hello World!</h2>
    		</div>
    	</lightning-card>
    </template>
    This markup defines a card base component with static text.
  6. Edit the helloWebComponent.js-meta.xml file, and replace <isExposed>false</isExposed>with these lines.
    <isExposed>true</isExposed>
    <targets>
    	<target>lightning__AppPage</target>
    	<target>lightning__RecordPage</target>
    	<target>lightning__HomePage</target>
    </targets>
    These extra lines allow you to add the component to any type of Lightning page in the Lightning App Builder.
  7. Deploy the updated code to the org. In VS Code, right-click the default folder and click SFDX: Deploy Source to Org.

Add the Hello World Component to a Page

Now that we have implemented our component, let’s add it to a page to view it.

  1. Open the org in a browser:
    sf org open
  2. From the App Launcher ( App Launcher), find and select Ursus Park. This opens the app Home page.
  3. Click the gear icon ( Setup Gear ) and select Edit Page.
  4. Under Custom Components, find your helloWebComponent component and drag it to the top of the right-hand column.
  5. Click Save.
  6. Since this is the first time we’ve modified the standard Home page, we need to activate the updated page so that our users can see what we’ve done. Click Activate.
  7. Click App Default tab.
  8. Click Assign to Apps.
  9. Check Ursus Park.
  10. Click Next and then Save.
  11. Click BackBack button to return to the Home page.

Your static Lightning Web Component on the Ursus Park Home page

Congratulations! You’ve just created your first Lightning web component and added it to a page in Lightning Experience. This first version doesn’t do much, so let’s turn it into something a bit more dynamic.

Use Data Binding

Let’s add some data to our component. We’ll work with one-way data binding. We start by displaying read-only data then make it editable.

  1. In VS Code, click helloWebComponent.html to edit it. Replace <h2>Hello World!</h2> with <h2>Hello {greeting}!</h2>. This adds a binding to a greeting property that we define in the next step.
  2. Edit helloWebComponent.jsand replace its contents with the following.
    import { LightningElement } from 'lwc';
    export default class HelloWebComponent extends LightningElement {
    	greeting = 'Trailblazer';
    }
    This declares and initializes a greeting property. This property is reactive. In other words, whenever the value of greeting changes, the component’s HTML template is automatically refreshed.
  3. Deploy the updated code to the org. Right-click the default folder and click SFDX: Deploy Source to Org.
  4. In the org, refresh the Ursus Park Home page and notice that your component changed (it's now displaying “Hello Trailblazer!” instead of “Hello World!”).

Well done! You have achieved data binding: the greeting property is read and displayed, but it cannot be modified by the user for now.

Let’s go one step further and make the data editable by adding an input field.

  1. In VS Code, edit helloWebComponent.html and add the following line under <h2>Hello {greeting}!</h2>:
    <lightning-input
    label="Name"
    value={greeting}
    onchange={handleGreetingChange}
    ></lightning-input>
    This code adds a text input field styled with SLDS. The input is initialized with the greeting property. Whenever the input changes, it calls a handleGreetingChange JavaScript function that we define in the next step.
  2. Edit helloWebComponent.js and add the following lines under greeting = 'Trailblazer';.
    handleGreetingChange(event) {
    	this.greeting = event.target.value;
    }
    This defines a function that captures a value from an event (input change event coming from the input field) and assigns it to the greeting property.
  3. Deploy the updated code to the org. Right-click the default folder and click SFDX: Deploy Source to Org.
  4. In the org, refresh the Home page and notice how your component is instantly updated when you edit the text field.

Your Lightning Web Component with data binding on the Ursus Park Home page

You have established data binding and made your data editable. The greeting property is displayed and automatically refreshed whenever you change its value with the input field.

Displaying a property is a start, but what if you need to transform its value before rendering it? Lightning Web Components have you covered with expressions.

Use Expressions

Let’s get into some more advanced topics and use an expression to display a dynamic value. We’ll add an expression that returns a greeting message with your name in capital letters.

  1. In VS Code, edit helloWebComponent.html and replace title="Lightning Web Component" with title={capitalizedGreeting}.
  2. Replace <h2>Hello {greeting}!</h2> with <p>Today is {currentDate}</p>.
  3. Edit helloWebComponent.js and add the following lines above the handleGreetingChangefunction block.
    currentDate = new Date().toDateString();
    get capitalizedGreeting() {
    	return `Hello ${this.greeting.toUpperCase()}!`;
    }
    This defines a currentDate class property and a capitalizedGreeting getter function. These getter functions are called expressions. They are used to display values just like properties, but expression values can be calculated based on some logic written in a function. Unlike properties, expressions aren't reactive: they are automatically reevaluated each time the component rerenders. This holds true whether their value has changed or not. When a user types something in the input of the component, the handleGreetingChange event handler function updates the value of the greeting property. Since greeting is reactive, it triggers a rerender, which forces the reevaluation of expressions. Note that we declared a currentDate class property to hold and display the current date instead of using an expression. We could also write an expression with just return new Date().toDateString(); but using a property has the benefit of not creating a new Date object for each rerender.
  4. Deploy the updated code to the org. Right-click the default folder and click SFDX: Deploy Source to Org.
  5. In the org, refresh the Home page and notice how the expressions are displayed.

Your Lightning Web Component with expressions on the Ursus Park Home page

As you can see, expressions allow us to keep component templates clear of logic. In fact, using expressions is the only way to transform a property value before displaying it.

That’s it for this step. You’ve set up a basic hello world component with base components, data binding, and expressions.

Now that we’ve covered the basics, let’s move on to something more exciting.

Salesforce 도움말에서 Trailhead 피드백을 공유하세요.

Trailhead에 관한 여러분의 의견에 귀 기울이겠습니다. 이제 Salesforce 도움말 사이트에서 언제든지 새로운 피드백 양식을 작성할 수 있습니다.

자세히 알아보기 의견 공유하기