Handling Events & Component Communication
Communicate between components: DOM events, custom events with detail, and parent-child versus unrelated patterns.
Handling events & component communication
Components rarely live alone, so communication between them is essential. LWC follows the web-standard event model, and the guiding principle is data down, events up: parents pass data to children through public properties, and children notify parents by dispatching events. Getting this direction right keeps components reusable and reasoning simple.
A parent passes data down by exposing a public property on the child with the @api decorator, then binding to it in markup. A child sends data up by creating and dispatching a CustomEvent, optionally carrying a payload in its detail. The parent listens with an on-prefixed handler.
// Child: tile.js
import { LightningElement, api } from 'lwc';
export default class Tile extends LightningElement {
@api product; // set by the parent
handleSelect() {
// Notify the parent, passing data in detail
this.dispatchEvent(new CustomEvent('select', {
detail: { productId: this.product.id }
}));
}
}
<!-- Parent template -->
<template for:each={products} for:item="p">
<c-tile key={p.id} product={p} onselect={handleSelect}></c-tile>
</template>
In the parent's handleSelect(event) you read event.detail.productId to know which tile fired. A few rules keep events clean: event names are lowercase with no spaces, dispatched via this.dispatchEvent(), and by default they don't cross the shadow boundary unless you set bubbles and composed — which you should use sparingly because it couples components. Prefer targeted parent-child events over broadly bubbling ones.
Not all components are in a parent-child relationship, though. For sibling or unrelated components, use the Lightning Message Service (LMS), which publishes and subscribes to messages over a message channel across the DOM — even between LWC, Aura, and Visualforce. For deep component trees you can also use the pubsub pattern, but LMS is the supported, modern choice. Choose the lightest mechanism that fits: @api down and CustomEvent up within a hierarchy, LMS across the page. With components talking to each other, the next step is bringing in real Salesforce data.