Sub topic 6
What Lightning Web Components are
Prerequisites
This chapter assumes you know basic HTML and CSS, JavaScript classes and arrow functions, and how the browser DOM and event listeners work. It also assumes you have seen the web component standards from earlier chapters: custom elements, shadow DOM, templates and slots, and ES modules. Here they are combined into one framework.
What LWC is
Lightning Web Components (LWC) is a framework for building user interface components on top of web component standards. It exists in two forms:
- The Salesforce platform, where LWC runs inside Lightning Experience, Experience Cloud, and the Salesforce mobile app.
- The open-source LWC project, which you can use to build components outside Salesforce.
An LWC component is a JavaScript class that extends LightningElement. The framework registers that class as a custom element and renders its template into a shadow root. A component is therefore a real DOM element, and the browser treats it like any other element.
LWC replaced the older Aura component model on the platform. Aura used its own component system, with its own event model and a large runtime. As browsers added native support for custom elements, shadow DOM, and ES modules, Salesforce moved to a model that uses those features directly. The result is a smaller framework layer and code that looks like ordinary modern JavaScript.
Why it exists
The goal is to do as little as possible in framework code and to leave the rest to the browser. That choice has three practical effects:
- Skills carry over. Classes, modules, events, and the DOM work as you already know them.
- Less framework code. Features the browser provides natively do not need to be rebuilt in JavaScript.
- Interoperability. A component is a custom element, so other code can create it, read its public properties, and listen for its events.
Plain web component versus LWC
Compare a hand-written web component with the LWC version of the same idea. First, the plain version.
class HelloGreeting extends HTMLElement {
connectedCallback() {
const root = this.attachShadow({ mode: 'open' });
const name = this.getAttribute('name') ?? 'World';
root.innerHTML = `<p>Hello, ${name}!</p>`;
}
}
customElements.define('hello-greeting', HelloGreeting);You do everything by hand here. You attach the shadow root, read the attribute, build the markup as a string, and register the tag name. Nothing updates if the name changes later.
The LWC version splits the work across files. The template comes first.
<!-- helloGreeting.html -->
<template>
<p>Hello, {name}!</p>
<input type="text" value={name} onchange={handleChange} />
</template>The class comes next.
// helloGreeting.js
import { LightningElement } from 'lwc';
export default class HelloGreeting extends LightningElement {
name = 'World';
handleChange(event) {
this.name = event.target.value;
}
}You never call attachShadow or customElements.define. The framework does both. The {name} expression reads the class field, and the onchange attribute binds a method as an event listener. When handleChange assigns a new value to this.name, the framework re-renders the part of the template that uses it.
How an LWC component maps onto the standards
The table shows which standard each part of an LWC component corresponds to.
| LWC piece | Standard it builds on | What LWC adds |
|---|---|---|
| Component class | Custom element (`HTMLElement`) | `LightningElement` base class, registration done for you |
| Rendered output | Shadow root | Automatic creation and rendering of the template into it |
| `<template>` file | HTML template element | Expressions in braces, directives, compile-time checks |
| Each file as a module | ES modules | Resolving `lwc` and `c/` imports |
| `onchange={handler}` | DOM event listeners | Declarative binding syntax in templates |
| `CustomEvent` | DOM events | None. This is the standard API. |
The diagram shows the path from your files to a running element.
The component bundle
Each component lives in a folder named after the component, and that folder is called a bundle. A bundle holds these files, all sharing the folder name:
helloGreeting.html: the template. Optional only for components that render nothing, such as utility modules.helloGreeting.js: the class and its logic. Required.helloGreeting.css: styles scoped to this component. Optional.helloGreeting.js-meta.xml: configuration for the Salesforce platform. Needed to place the component in the Lightning App Builder or on pages.
The metadata file sets the API version and where the component can be used.
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>The metadata file is a Salesforce concept. The open-source LWC project does not use it.
Public properties and events
Components talk to each other through two channels. A parent passes data down through public properties. A child sends information up through events.
A child marks a field as public with the @api decorator, and it dispatches a standard CustomEvent.
// counterButton.js
import { LightningElement, api } from 'lwc';
export default class CounterButton extends LightningElement {
@api label = 'Add';
count = 0;
handleClick() {
this.count += 1;
this.dispatchEvent(
new CustomEvent('countchange', { detail: { count: this.count } })
);
}
}The parent sets the property in markup and listens with an on prefix.
<!-- parentPanel.html -->
<template>
<c-counter-button label="Increase" oncountchange={handleCountChange}></c-counter-button>
</template>The event countchange is listened for as oncountchange. Here the parent sets label on the child. The child never changes label itself. A public property belongs to the parent that set it, and the child should treat it as read-only.
Rendering lists
Templates can repeat elements with the for:each directive. Each repeated element needs a unique key.
<!-- todoList.html -->
<template>
<ul>
<template for:each={items} for:item="item">
<li key={item.id}>{item.label}</li>
</template>
</ul>
</template>The key lets the framework match old and new items when the list changes, so it updates only what differs.
Common errors
- Missing
keyin a list. The compiler rejectsfor:eachcontent without akeyon the first child element. - Using an expression in an attribute. Templates accept only a simple property reference in braces, such as
{name}. Write computed values as getters in the class, not as inline expressions like{a + b}. - Wrong event name in the parent. Event names should be lowercase with no spaces or hyphens, and the handler attribute is
onplus that name. - Expecting a tag to match the folder name exactly.
helloGreetingbecomesc-hello-greeting. Writing<c-helloGreeting>does not work, because HTML tag names are case-insensitive. - Mutating a public property in the child. The framework protects it, and changes can be rejected or lost. Copy the value into a private field first.
- Assuming CSS leaks out or in. The component's CSS applies only inside its own shadow root, and a parent's CSS does not reach in.
Standard features and LWC additions
Most of what you write in an LWC is standard: classes, modules, CustomEvent, dispatchEvent, the DOM, and the shadow root. The framework adds a smaller set of things:
- The
LightningElementbase class and its lifecycle methods. - The
@apidecorator, and the related@trackand@wiredecorators covered later. - Template syntax: braces, directives such as
for:each, andonevent bindings. - A compiler that turns templates and classes into modules, and checks them.
- Platform services: base components, the metadata file, and data access.
Later chapters take each of these in turn. For now, hold on to the working model. An LWC component is a custom element whose class extends LightningElement, whose template renders into a shadow root, and whose public surface consists of @api properties and DOM events.
Exercise
A component folder is named userCard. Which tag do you use in another component's template, and which two things does the framework do for you that a plain web component would do by hand?
Show answer
You use <c-user-card>, assuming the default c namespace. The framework registers the class as a custom element (the customElements.define step) and attaches a shadow root and renders the template into it (the attachShadow step).
Exercise
A child component dispatches new CustomEvent('save', { detail: { id: 7 } }). Write the parent template line that listens for it on <c-editor>, and say how the handler reads the id.
Show answer
<c-editor onsave={handleSave}></c-editor>. In the parent class, handleSave(event) reads event.detail.id.
Exercise
A teammate writes <li>{item.label}</li> inside a for:each template and the compiler reports an error. What is missing, and why is it needed?
Show answer
The <li> needs a unique key attribute, such as key={item.id}. The framework uses the key to match existing items with the updated list, so it can change only the elements that differ.