Sub topic 4
The JavaScript class
This chapter assumes you know ES modules and classes, and that you have seen a Lightning web component folder in a Salesforce DX project. The HTML template, CSS file and configuration file each get their own chapter. Here the focus is the .js file that holds the component's behavior.
What the file does
The JavaScript file defines the component's behavior and data. It has to default-export one class that extends LightningElement. The template reads values from that class, and event handlers in the template call methods on it.
import { LightningElement, api } from 'lwc';
export default class GreetingCard extends LightningElement {
@api name = 'World';
}Three things in this file are required:
- The file's base name matches the bundle folder, so
greetingCard/greetingCard.js. LightningElementis imported from thelwcmodule.- The class is the default export. A named export alone compiles but never renders, because the framework looks for the default export.
The class name is conventionally the PascalCase form of the folder name (greetingCard becomes GreetingCard). The framework does not check this. The file name and the default export are what matter, but a mismatched class name makes stack traces and tests harder to read.
Fields and reactivity
A field is a property declared in the class body. Every field is reactive. If a field is used in the template and its value changes, the component re-renders.
import { LightningElement, api, track } from 'lwc';
export default class GreetingCard extends LightningElement {
@api name = 'World';
clicks = 0;
@track profile = { city: 'Paris' };
handleClick() {
this.clicks += 1;
this.profile.city = 'Lyon';
}
}Reassigning a field, as in this.clicks += 1, always triggers a re-render. Changing a property inside an object or array is different. The framework observes only the field itself, not what is inside it, unless the field is decorated with @track. Here this.profile.city = 'Lyon' updates the template because profile is tracked. Without @track you would need to replace the whole object:
this.profile = { ...this.profile, city: 'Lyon' };Replacing the object works with or without @track, and many teams prefer it for that reason.
Fields that the template never reads do not cause re-renders. A field with a value that is only used in a method is plain state.
Decorators
LWC provides three decorators. They are imported from lwc alongside LightningElement.
| Decorator | Purpose | Notes |
|---|---|---|
| `@api` | Makes a property or method public | A parent component, App Builder or a test can set it or call it |
| `@track` | Observes changes inside an object or array | Not needed for primitives or for replacing whole values |
| `@wire` | Connects a field or function to a data service | Used for Apex and Lightning Data Service, covered in later tutorials |
Public properties with @api
A property marked @api is part of the component's public contract. The parent sets it in markup, and the configuration file can expose it in App Builder.
@api name = 'World';A parent that uses <c-greeting-card name="Ada"> sets name to Ada. Inside the component, @api values are read-only. The class should not assign to this.name when the value came from a parent. If the component needs a changed version, copy it into a separate field or use a getter.
Public property names have restrictions. They cannot start with on, aria or data, and they cannot be class, slot, style or is, because those collide with standard HTML attributes. In the parent's markup, a camelCase property such as maxItems is written as the kebab-case attribute max-items.
Public methods
@api on a method lets a parent call it through a reference to the element:
@api reset() {
this.clicks = 0;
}Prefer public properties and events for most communication. Public methods suit imperative actions such as focus() or reset().
Getters and setters
A getter computes a value from other fields. The template can bind to it as if it were a field.
get message() {
return `Hello, ${this.name}!`;
}If a public property needs a setter, put @api on only one of the pair, usually the getter. Decorating both is a compile error.
_count = 0;
@api
get count() {
return this._count;
}
set count(value) {
this._count = Math.max(0, Number(value) || 0);
}Lifecycle hooks
The framework calls certain methods at fixed points in a component's life. You define the ones you need.
| Hook | Runs | Typical use |
|---|---|---|
| `constructor()` | When the instance is created | Set initial state. Call `super()` first |
| `connectedCallback()` | When the component is inserted into the DOM | Load data, subscribe to events |
| `render()` | Before each render | Pick a template (see the multiple templates chapter) |
| `renderedCallback()` | After each render | Work with the rendered DOM |
| `disconnectedCallback()` | When the component is removed | Undo what `connectedCallback` set up |
| `errorCallback(error, stack)` | When a child throws | Show a fallback and log the error |
Two details cause most mistakes:
- In the constructor, the component has no children, no public properties from the parent and no attributes. Do not read
this.namethere, and do not add attributes to the host element. renderedCallbackruns after every render, not only the first. If it changes a tracked field, it triggers another render and can loop. Guard such work with a flag.
import { LightningElement, api } from 'lwc';
export default class GreetingCard extends LightningElement {
@api name = 'World';
clicks = 0;
hasRendered = false;
connectedCallback() {
console.log(`Connected with name: ${this.name}`);
}
renderedCallback() {
if (this.hasRendered) {
return;
}
this.hasRendered = true;
const p = this.template.querySelector('p');
console.log(p ? p.textContent : 'No paragraph found');
}
handleClick() {
this.clicks += 1;
}
}In connectedCallback, the parent's public property values are already set, so this.name is safe to read there.
Reaching the rendered DOM
Inside the class, this.template is the root of the component's own shadow tree. Use this.template.querySelector() to find elements the component rendered. The method does not see elements inside child components. Outside the component, such as in a Jest test, the same tree is reached with element.shadowRoot.
this.refs is a newer alternative. It reads elements the template marks with lwc:ref, and it is available from API version 59.0 onward.
What belongs in the class
Keep the class focused on the component's state and behavior. Code that several components need, such as formatting functions or constants, belongs in a helper module in the same bundle or in a separate service component. The helper modules chapter covers that.
Imports other than lwc also go at the top of this file. They include Apex methods (@salesforce/apex/...), custom labels (@salesforce/label/...), schema references and other components' modules.
Common errors
- Missing default export. The component compiles, then renders nothing or the deployment fails. Use
export default class. - Missing
super()in a constructor. A constructor must callsuper()before touchingthis. - Mutating an
@apiproperty. The change is rejected or ignored. Copy the value into a private field. - Mutating inside an object without
@track. The template stays stale. Replace the object or add@track. - Setting state in
renderedCallbackwithout a guard. This causes repeated renders. - File name differs from the folder name. The module is not found, and the component tag does not resolve.
Exercise
A component has a field @track missing: items = ['a', 'b']. A handler runs this.items.push('c'), but the list in the template does not update. Give two ways to fix it.
Show answer
Reassign the field instead of mutating it, for example this.items = [...this.items, 'c'];. Or decorate the field with @track so that changes inside the array are observed. Reassigning is usually preferred because it works without the decorator.
Exercise
Why is it a mistake to read this.name in the constructor of a component whose parent sets name?
Show answer
The constructor runs when the instance is created, before the parent's property values are assigned and before the component is connected. this.name would still hold its default. Read it in connectedCallback instead.