Sub topic 1
Templates, Data Binding and the Shape of List Data
This chapter sets up the working model you need before you render lists in a Lightning Web Component (LWC). It covers how a template reads data from its class, which data shapes suit list rendering, and which mistakes to avoid. Later chapters build on this with for:each and iterator.
Prerequisites
This chapter assumes you already know the following:
- Basic HTML and JavaScript, including arrays, object literals, spread syntax and the
mapmethod. - How an LWC component is structured: an HTML template file and a JavaScript class that extends
LightningElement, both in a folder with the same name. - How to bind a class property in a template with curly braces, such as
{greeting}. - Basic conditional rendering with
lwc:ifandlwc:else.
You do not need to know for:each or iterator yet. Those come in the next chapters.
How a template reads data from its class
An LWC component has two halves. The JavaScript class holds data and behavior. The HTML template describes what the browser should show. The template can read anything the class exposes: fields, getters, and methods that are bound as event handlers.
<!-- greeting.html -->
<template>
<p>Hello, {name}!</p>
</template>// greeting.js
import { LightningElement } from 'lwc';
export default class Greeting extends LightningElement {
name = 'Amy';
}The braces {name} are a binding. The framework looks up name on the component instance and puts its value in the page. When the value changes, the framework updates only the part of the page that depends on it.
A few rules matter for lists:
- A binding must be a plain property path, such as
{name}or{contact.Name}. The path can go deeper into an object. - A binding cannot hold an expression.
{name.toUpperCase()},{count + 1}and{a === b}are all invalid in a template. - Anything that needs calculation belongs in the class, usually as a getter.
Getters for computed values
A getter is a class member that looks like a property but runs code each time the template reads it. Use one whenever the template needs a derived value.
import { LightningElement } from 'lwc';
export default class Summary extends LightningElement {
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' }
];
get contactCount() {
return this.contacts.length;
}
get hasContacts() {
return this.contacts.length > 0;
}
}<template>
<p>Total contacts: {contactCount}</p>
<p lwc:if={hasContacts}>The list has data.</p>
<p lwc:else>The list is empty.</p>
</template>The template never computes contacts.length > 0 itself. The getter does that, and the template only reads the result.
The shape of list data
A list in a template is rendered from an array. Each element of that array is usually a plain object, with one property per piece of information you want to show. The data for the later chapters looks like this:
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' },
{ Id: '003C', Name: 'Lena Fischer' }
];Three properties of this shape matter.
- It is an array. Directives for lists work on arrays (and other iterable values). A single object, a string or a number is not a list.
- Each element is an object with named properties. The template reaches into an item with a path like
contact.Name. - Each element has a unique identifier. Here that is
Id. The framework uses a unique value to tell items apart when the list changes. The chapter on keys covers this in detail. For now, remember that data without a stable unique value is hard to render correctly.
Where list data comes from
In real components, the array usually arrives from one of these sources:
| Source | Typical shape | Identifier |
|---|---|---|
| Hard-coded class field | Array of plain objects | You choose it |
| Apex method or wire adapter | Array of records | `Id` field of each record |
| Parent component through a public property | Array of plain objects | Set by the parent |
| Built in the class with `map` | Array of new objects | Copied or generated |
Records returned from Apex usually already carry an Id. If your data comes from somewhere that has no identifier, add one when you build the array rather than later in the template.
Reading nested values
Bindings follow property paths into nested objects. Given this data:
account = {
Name: 'Northwind',
Owner: { Name: 'Sam Lee' }
};The template can bind {account.Name} and {account.Owner.Name}. If a link in the path is undefined, the binding shows nothing. It does not throw an error in the template, but it also hides the problem. If a field is blank in the page, check that the path matches the data.
Reactivity: when the template updates
The template redraws when a value it reads changes. In current LWC, class fields are reactive. The rules that affect lists are these:
- Assigning a new value to a field triggers a re-render. For example,
this.contacts = newArray;does. - Changing a field that holds an object or array, and that is not reassigned, is tracked in many cases for plain objects and arrays declared as fields. Do not rely on this for lists. The supported, predictable pattern is to build a new array and assign it.
- Data passed in from a parent through a public property is read-only in the child. If you need to change it, copy it first.
addContact() {
// Build a new array and assign it to the field.
this.contacts = [
...this.contacts,
{ Id: '003D', Name: 'New Contact' }
];
}The chapter on updating lists returns to this. The habit to start now is: build a new array and assign it.
A first look at the whole flow
The diagram shows how data moves from the class to the page, and where computation has to happen.
Common errors at this stage
- Writing an expression in braces.
{contacts.length > 0}is rejected. Move it into a getter. - Binding a method call.
{getName()}is not allowed either. Use a getter and bind{name}. - Expecting a mutation to redraw the page. Changing an item deep inside an array may not give you the update you expect. Assign a new array.
- Starting without identifiers. Data with no unique value per item forces workarounds later. Add an identifier when you build the array.
- Mixing up the file names. The JavaScript file, HTML file and folder must share a name, such as
contactList/contactList.jsandcontactList/contactList.html. A mismatch means the template is not found.
Wrapping primitive values
Sometimes you start with a simple array, such as colors. Convert it to objects with map so every item has the properties a template needs.
import { LightningElement } from 'lwc';
export default class ColorList extends LightningElement {
rawColors = ['Red', 'Green', 'Blue'];
get colors() {
return this.rawColors.map((label, index) => ({
id: `color-${index}`,
label
}));
}
}The getter returns an array of objects, each with an id and a label. A template can now bind {color.label} and use color.id as an identifier. This works because the colors are fixed here. If the order or contents of the list can change, derive the identifier from the value, such as the label, when it is unique. An index-based identifier is a weak choice for lists that change. Chapter four explains why.
Exercise
A template needs to show "No contacts" when contacts is empty, and the developer writes <p lwc:if={contacts.length === 0}>No contacts</p>. Why does this fail, and how do you fix it?
Show answer
Template bindings accept only property paths, not expressions, so contacts.length === 0 is invalid. Add a getter such as get isEmpty() { return this.contacts.length === 0; } to the class and write <p lwc:if={isEmpty}>No contacts</p>.
Exercise
A component has labels = ['North', 'South', 'East']. What shape should the data have before you render it as a list, and what would you add to each item?
Show answer
Convert it to an array of objects, for example with map, so each item is { id: 'north', label: 'North' }. The id gives each item a unique, stable identifier for later use as a key, and the label is the value the template binds.