Sub topic 8
Handling events and passing data
Base components report user actions through events. They take data from their parent through attributes. This chapter covers both directions of that flow and the mistakes that most often break it. It assumes you can read an LWC template and class, and that you have used lightning-input and lightning-button as shown in earlier chapters.
The direction of data flow
LWC data flow is one-way. Data goes down through properties and attributes. Information goes up through events.
- A parent passes values to a child with attributes such as
label={title}. The child receives them as public properties, marked@apiif it is a custom component. - A child tells its parent something happened by dispatching a DOM event. The parent listens with an
on<eventname>attribute.
Base components follow the same rules. When you write value={searchKey}, you are passing data down. When you write onchange={handleChange}, you are listening for data coming up.
Listening to base component events
Attach a handler in the template with on followed by the lowercase event name. The handler is a method on your class, referenced without parentheses.
<template>
<lightning-input
type="search"
label="Name"
value={searchKey}
onchange={handleChange}
></lightning-input>
<lightning-input
type="checkbox"
label="Active only"
checked={activeOnly}
onchange={handleActive}
></lightning-input>
<lightning-combobox
label="Status"
value={status}
options={statusOptions}
onchange={handleStatus}
></lightning-combobox>
</template>import { LightningElement } from 'lwc';
export default class FilterBar extends LightningElement {
searchKey = '';
activeOnly = false;
status = 'all';
statusOptions = [
{ label: 'All', value: 'all' },
{ label: 'Open', value: 'open' },
{ label: 'Closed', value: 'closed' }
];
handleChange(event) {
this.searchKey = event.target.value;
}
handleActive(event) {
this.activeOnly = event.target.checked;
}
handleStatus(event) {
this.status = event.detail.value;
}
}Each base component puts its result in a different place on the event.
| Component | Where to read the new value |
|---|---|
| `lightning-input` (text, search, number) | `event.target.value` |
| `lightning-input` (checkbox, toggle) | `event.target.checked` |
| `lightning-combobox` | `event.detail.value` |
| `lightning-datatable` row selection | `event.detail.selectedRows` |
Check the component's documentation page for the event's detail shape. If a value comes back undefined, you are probably reading from target when the component puts it in detail, or the reverse.
event.target and event.currentTarget
event.target is the element that dispatched the event. event.currentTarget is the element your handler is attached to. For a base component handler written in your own template, these are usually the same element, the lightning-* host. Use event.target for the usual cases. Prefer currentTarget when the handler sits on a wrapper element and you want that wrapper, not whatever was clicked inside it.
To know which row or item triggered an event, put a data- attribute on the element and read it from dataset:
<template>
<template for:each={contacts} for:item="contact">
<lightning-button
key={contact.id}
label={contact.name}
data-id={contact.id}
onclick={handleSelect}
></lightning-button>
</template>
</template>import { LightningElement } from 'lwc';
export default class ContactButtons extends LightningElement {
contacts = [
{ id: '1', name: 'Ada Lovelace' },
{ id: '2', name: 'Grace Hopper' }
];
handleSelect(event) {
const contactId = event.target.dataset.id;
console.log('Selected', contactId);
}
}data-id becomes dataset.id. A name such as data-contact-id becomes dataset.contactId. All dataset values are strings, so convert numbers yourself.
Sending data down with @api
A custom child component exposes properties to its parent with @api. The parent sets them like attributes. Attribute names use kebab-case in the template and camelCase in JavaScript.
import { LightningElement, api } from 'lwc';
export default class ContactList extends LightningElement {
@api contacts = [];
@api heading = 'Contacts';
}<c-contact-list heading="Team" contacts={contacts}></c-contact-list>Sending data up with custom events
To notify a parent, create a CustomEvent and dispatch it from the component. Put any payload in detail.
import { LightningElement, api } from 'lwc';
export default class ContactList extends LightningElement {
@api contacts = [];
handleSelect(event) {
const contactId = event.target.dataset.id;
this.dispatchEvent(
new CustomEvent('contactselect', { detail: { contactId } })
);
}
}The parent listens with on plus the event name:
<template>
<c-contact-list
contacts={contacts}
oncontactselect={handleContactSelect}
></c-contact-list>
<p>Selected: {selectedId}</p>
</template>import { LightningElement } from 'lwc';
export default class ContactPage extends LightningElement {
selectedId;
contacts = [
{ id: '1', name: 'Ada Lovelace' },
{ id: '2', name: 'Grace Hopper' }
];
handleContactSelect(event) {
this.selectedId = event.detail.contactId;
}
}Follow these rules for event names:
- Use only lowercase letters, numbers and underscores. Do not use hyphens or uppercase.
- Do not start the name with
on. - Avoid names of native DOM events such as
select,changeorclick. A customselectevent can collide with the native one.
By default a custom event does not bubble and is not composed. Only a direct parent can hear it. Setting bubbles: true and composed: true lets it cross shadow boundaries, but it then reaches every ancestor and couples components together. Leave both off unless you have a clear reason.
Events from lightning-datatable
lightning-datatable reports row selection and row actions as events. The payload is in detail.
<template>
<lightning-datatable
key-field="id"
data={contacts}
columns={columns}
onrowselection={handleRowSelection}
onrowaction={handleRowAction}
></lightning-datatable>
</template>import { LightningElement } from 'lwc';
export default class ContactTable extends LightningElement {
columns = [
{ label: 'Name', fieldName: 'name', type: 'text' },
{
type: 'action',
typeAttributes: {
rowActions: [{ label: 'View', name: 'view' }]
}
}
];
contacts = [
{ id: '1', name: 'Ada Lovelace' },
{ id: '2', name: 'Grace Hopper' }
];
selectedIds = [];
handleRowSelection(event) {
this.selectedIds = event.detail.selectedRows.map((row) => row.id);
}
handleRowAction(event) {
const actionName = event.detail.action.name;
const row = event.detail.row;
if (actionName === 'view') {
console.log('Viewing', row.name);
}
}
}selectedRows holds copies of the row objects. Compare rows by the key field, not by object identity.
Reducing handler work
lightning-input fires change on every keystroke. If each keystroke triggers a server call or a heavy filter, wait until typing pauses. Store a timer and clear it each time.
import { LightningElement } from 'lwc';
export default class DebouncedSearch extends LightningElement {
searchKey = '';
delayTimeout;
handleChange(event) {
const value = event.target.value;
window.clearTimeout(this.delayTimeout);
this.delayTimeout = window.setTimeout(() => {
this.searchKey = value;
}, 300);
}
disconnectedCallback() {
window.clearTimeout(this.delayTimeout);
}
}Read event.target.value before the timer starts, as shown. Do not read the event inside the delayed callback.
Common errors
| Symptom | Likely cause |
|---|---|
| Handler never runs | Event name is wrong, or the handler is written `onchange={handleChange()}` with parentheses |
| `undefined` value | Reading `target.value` when the component uses `detail.value`, or the reverse |
| Input resets while typing | The `value` attribute is bound to a field that the handler does not update |
| Parent does not receive a custom event | The event name has uppercase or hyphens, or the listener is on a non-parent ancestor and the event does not bubble |
| Error about a read-only property | A child assigned to an `@api` property it received from a parent |
Exercise
A child component dispatches new CustomEvent('itemSelected', { detail: { id: '7' } }). The parent writes onitemSelected={handleItem}, and the handler never runs. What two things should you change, and how does the handler then read the id?
Show answer
Rename the event to lowercase with no hyphens, for example itemselected, and change the listener to onitemselected={handleItem}. Inside the handler, read the payload with event.detail.id.
Exercise
A text input is bound with value={name} and onchange={handleChange}, but the typed text disappears on re-render. The handler contains console.log(event.target.value) only. What is missing?
Show answer
The handler must store the value in the bound field with this.name = event.target.value;. Without it, the template re-renders with the old name and the input resets.