Sub topic 1
Quick recap: anatomy of a Lightning web component
This chapter refreshes the parts of a Lightning web component (LWC) that the rest of the tutorial builds on. Later chapters use base components (the lightning-* elements) and the Salesforce Lightning Design System (SLDS). Both depend on how a component's template, class, and stylesheet fit together.
Prerequisites
This chapter assumes you have:
- Basic HTML, CSS, and modern JavaScript, including classes and ES modules.
- Seen a Lightning web component before, with its HTML template, JavaScript class, and CSS file.
- Access to a Salesforce org or scratch org where you can deploy and preview components.
You do not need to know any base components yet. The next chapter introduces them.
The component bundle
A Lightning web component is a folder that holds files with matching names. The folder name is the component name. The files inside use that name as their base.
force-app/main/default/lwc/contactSearch/
├── contactSearch.html
├── contactSearch.js
├── contactSearch.css
├── contactSearch.js-meta.xml
└── __tests__/
└── contactSearch.test.js| File | Purpose | Required |
|---|---|---|
| `contactSearch.html` | The template that describes the markup | Only for components that render UI |
| `contactSearch.js` | The class that holds state and behavior | Yes |
| `contactSearch.css` | Styles that apply to this component only | No |
| `contactSearch.js-meta.xml` | Metadata: API version and where the component can be used | Yes, to deploy |
| `__tests__/` | Jest tests that run outside the org | No |
Folder names use camelCase, such as contactSearch. In markup, you refer to the component with a kebab-case tag that includes its namespace. A component in the default c namespace appears as <c-contact-search>. Base components use the lightning namespace, so lightning-card is the card component in that namespace.
The template
The template is an HTML file whose root element is <template>. Everything you render goes inside it.
<template>
<lightning-card title="Contact search" icon-name="standard:contact">
<lightning-button
slot="actions"
label="Clear"
onclick={handleClear}
></lightning-button>
<div class="slds-var-p-around_medium">
<lightning-input
type="search"
label="Name"
value={searchKey}
onchange={handleChange}
></lightning-input>
</div>
</lightning-card>
</template>Four template features appear in this short example, and you will see them in every chapter that follows:
- Child components.
lightning-card,lightning-button, andlightning-inputare custom elements. The template composes them like ordinary HTML tags. - Attributes. Static values are plain strings, such as
label="Clear". In markup, multi-word property names use kebab-case (icon-name). In JavaScript, the same property is camelCase (iconName). - Bindings. Curly braces connect the template to the class.
value={searchKey}reads thesearchKeyfield. The braces hold a property name only. You cannot write an expression like{searchKey.length > 3}. - Event handlers.
onclick={handleClear}registers a listener. The name afteronis the event name, and the value is a method on the class.
The slot="actions" attribute places the button in a named slot of lightning-card. Slots let a parent pass markup into a child. Base components use them for areas such as card actions and footers.
The JavaScript class
Every component class extends LightningElement. This base class gives you the component lifecycle, access to the template's DOM, and the ability to dispatch events.
import { LightningElement } from 'lwc';
export default class ContactSearch extends LightningElement {
searchKey = '';
handleChange(event) {
this.searchKey = event.target.value;
}
handleClear() {
this.searchKey = '';
}
}The class must be the default export of its module. The platform finds the component through that export.
Reactive fields
Class fields are reactive. When you assign a new value to a field that the template uses, the component re-renders the parts of the template that depend on it. In the example, handleClear sets searchKey to an empty string. The template re-renders, and the lightning-input receives the new value.
This is why the Clear button works. The input reports the user's typing through onchange, but the class owns the value. Setting the field is what changes what the input shows.
There is one limit to know now. Reactivity tracks reassignment of a field. For objects and arrays, the platform also tracks changes to the properties of plain objects and the items of arrays that you reach through a field. Even so, the safest habit is to assign a new object or array when you update state. That habit avoids surprises when you pass the value to a child component.
Public properties and methods
A field is private to its component by default. To let a parent set it from markup, decorate it with @api.
import { LightningElement, api } from 'lwc';
export default class ContactBadge extends LightningElement {
@api contactName;
@api recordId;
@api
focusBadge() {
this.template.querySelector('.badge').focus();
}
}A parent then sets the property in its template:
<template>
<c-contact-badge contact-name="Ada Lovelace"></c-contact-badge>
</template>Base components work the same way. Attributes such as label, variant, and icon-name are @api properties on the base component's class. The documentation for each base component lists them, along with its public methods and events.
A child should treat the values it receives through @api as read-only. If the child needs a changed value, it dispatches an event and lets the parent decide. Chapter 8 covers that flow in detail.
The lifecycle at a glance
A component moves through a sequence of stages. You can run code at some of them by defining a method with a specific name.
The diagram below shows the order for a component that is created, shown, and then removed.
| Hook | Runs when | Typical use |
|---|---|---|
| `constructor()` | The component instance is created | Set initial values. Call `super()` first. |
| `connectedCallback()` | The component is inserted into the DOM | Load data, subscribe to messages |
| `renderedCallback()` | The template has rendered, after every render | Work with the rendered DOM |
| `disconnectedCallback()` | The component is removed from the DOM | Clean up listeners and subscriptions |
Two edge cases cause most lifecycle bugs:
- In
constructor()and the early part ofconnectedCallback(), the template has not rendered.this.template.querySelector(...)returnsnull. Wait forrenderedCallback(). renderedCallback()runs after every render, not just the first. If it changes a field that the template uses, it triggers another render. Guard such code with a flag so it does not loop.
import { LightningElement } from 'lwc';
export default class FocusOnLoad extends LightningElement {
hasFocused = false;
renderedCallback() {
if (this.hasFocused) {
return;
}
const input = this.template.querySelector('lightning-input');
if (input) {
input.focus();
this.hasFocused = true;
}
}
}The focus() method here is a public method that lightning-input exposes. This is a common way to interact with a base component from its parent.
Styles and the shadow DOM
A component's .css file applies to that component's template only. The platform enforces this with the shadow DOM, a browser feature that gives each component its own isolated DOM tree. Styles you write do not leak out to other components. Styles from other components do not leak in.
lightning-button {
--slds-c-button-brand-color-background: #0b5cab;
}This stylesheet targets the lightning-button element in your own template. It sets a CSS custom property, which is a value that the base component reads internally. It does not reach into the button's internal markup. Later chapters explain this mechanism, called styling hooks, and show how SLDS classes interact with the shadow DOM.
For now, keep one rule in mind. A selector in your CSS file matches only elements that appear in your own template. It cannot select elements inside a child component's shadow tree.
Composing a page from components
A component that holds other components is a parent. Each component is a boundary: the parent passes data down through @api properties and receives information up through events.
In the contact search example, ContactSearch is the parent and lightning-input is the child. The parent passes value down. The child sends change up. Almost every base component interaction in this tutorial follows this pattern.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The component does not appear in the app builder | `isExposed` is `false`, or no `targets` are listed in the meta file | Set `isExposed` to `true` and add targets |
| `{searchKey}` renders nothing | The field name is misspelled, or the field is declared in the template but not in the class | Match the name exactly, including case |
| A handler is never called | The attribute is `onClick` or the method name is misspelled | Use lowercase `onclick` and match the method name |
| `querySelector` returns `null` | The query runs before the first render | Move the query to `renderedCallback()` |
| The template shows `[object Object]` | An object is bound directly to text | Bind a specific property |
| Attribute does nothing on a base component | The attribute name is camelCase in markup | Use kebab-case, such as `icon-name` |
A minimal metadata file shows the first fix:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>61.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>What comes next
The following chapters add the pieces that make this structure useful. You will meet the base component library, learn the SLDS classes that style and lay out your markup, and build forms and tables. Every one of those pieces plugs into the same bundle: markup in the template, state in the class, and scoped styles in the CSS file.
Exercise
A component's connectedCallback() calls this.template.querySelector('lightning-input') and then calls focus() on the result. The component throws an error that the result is null. Why does this happen, and where should the code move?
Show answer
connectedCallback() runs when the component is inserted into the DOM, before its template has rendered, so the lightning-input does not exist yet and querySelector returns null. Move the code to renderedCallback(), check that the element exists, and use a flag so the focus call happens only once, because renderedCallback() runs after every render.
Exercise
In a parent template you write <lightning-card iconName="standard:contact" title="Contacts">. The title shows but the icon does not. What is wrong?
Show answer
In markup, multi-word property names must be written in kebab-case. The attribute should be icon-name, not iconName. The JavaScript property is iconName, but the template attribute is icon-name.