Sub topic 3
Handling Input and One-Way Data Flow
Assume basic HTML, modern JavaScript classes, and familiarity with an LWC bundle containing HTML, JavaScript, and meta XML files. In Lightning Web Components (LWC), data normally flows one way: a JavaScript field supplies a template value, and an event handler updates that field after user input.
Handling input
The template reads name through value={name}. When the input changes, handleChange receives an event and assigns the new value. The assignment causes the template to render again.
<!-- greeter.html -->
<template>
<lightning-input
label="Your name"
value={name}
onchange={handleChange}>
</lightning-input>
<p>{message}</p>
</template>// greeter.js
import { LightningElement } from 'lwc';
export default class Greeter extends LightningElement {
name = '';
handleChange(event) {
this.name = event.target.value;
}
get message() {
return this.name ? `Hello, ${this.name}!` : 'Please enter your name.';
}
}The template does not update the field automatically. This explicit flow makes the source of each change clear.
Changing objects and arrays
Reassigning a field is reactive:
this.items = [...this.items, 'Notebook'];The spread operator creates a new array. For plain objects and arrays, @track also observes in-place changes:
import { LightningElement, track } from 'lwc';
export default class Profile extends LightningElement {
@track address = { city: 'Paris' };
moveToLyon() {
this.address.city = 'Lyon';
}
}Prefer reassignment when practical. It makes updates easier to follow and avoids unnecessary tracking.
> callout tip > Do not mutate an object or array in place unless you understand its tracking behavior. Reassignment is usually the clearest choice.
Passing data to a child
A child exposes a public property with @api. A parent sets it with an attribute whose name uses kebab case.
// productCard.js
import { LightningElement, api } from 'lwc';
export default class ProductCard extends LightningElement {
@api productName;
}<c-product-card product-name={selectedName}></c-product-card>Public getter and setter pairs
Use a getter and setter when incoming data needs normalization. Decorate only one accessor.
@api
get quantity() {
return this._quantity;
}
set quantity(value) {
this._quantity = Math.max(0, Number(value) || 0);
}Getter pitfalls
A getter should calculate and return a value. It should not change fields, call server operations, or perform expensive work on every render. Keep transformations small, and prepare complex data when the source data changes.
Exercise
Why does an input handler assign event.target.value to a field?
Show answer
LWC uses one-way data flow, so the handler explicitly updates the field that the template reads.