Sub topic 12
Communicating upward with CustomEvent
This chapter assumes you know the prerequisites listed in the plan: JavaScript classes, the browser DOM, and event listeners. It also assumes you have seen @api properties from the previous chapter. Data flows down from parent to child through public properties. Data flows up from child to parent through DOM events. This chapter covers the upward direction.
Why events go up
A child component should not know who its parent is. If a child called a parent method directly, the two would be tightly coupled and the child could not be reused elsewhere. The DOM already has a solution. An element announces that something happened, and any ancestor that cares can listen.
LWC uses this pattern without adding a new mechanism. It uses the standard CustomEvent class and the standard dispatchEvent method.
| Direction | Mechanism | Standard or LWC addition |
|---|---|---|
| Parent to child | Public property set with `@api` | `@api` is an LWC decorator. Attributes and properties on elements are standard. |
| Child to parent | `CustomEvent` and `dispatchEvent` | Standard DOM |
| Parent listening in a template | `oneventname={handler}` | LWC template syntax over standard `addEventListener` |
Dispatching an event from a child
Here is the child from the topic's running example.
// counterButton.js
import { LightningElement, api } from 'lwc';
export default class CounterButton extends LightningElement {
@api label = 'Add';
count = 0;
handleClick() {
this.count += 1;
this.dispatchEvent(
new CustomEvent('countchange', { detail: { count: this.count } })
);
}
}Three parts matter here.
- The event name. The first argument to
CustomEventis a string. It iscountchangein this example. - The
detailproperty. The second argument is an options object. Whatever you put underdetailis available to listeners asevent.detail. This is the standard place for payload data. this.dispatchEvent.LightningElementinherits this from the standardEventTargetinterface. The event fires on the component's host element, which is the custom element that represents the component in the DOM.
Naming rules
Event names should be all lowercase. They should have no spaces, hyphens, or uppercase letters. Use a short name that describes what happened, such as countchange or select. The reason is the listener syntax in the parent template, shown next. The template turns on plus the event name into a listener, so the name must be a valid lowercase attribute-style token.
Listening in the parent
<!-- parentPanel.html -->
<template>
<c-counter-button label="Increase" oncountchange={handleCountChange}></c-counter-button>
</template>The attribute oncountchange is on plus countchange. The framework registers a listener for the countchange event on the child element and calls handleCountChange when it fires. The template does not create an inline HTML event attribute as in older plain HTML. The compiler converts the syntax to an addEventListener call.
The handler lives in the parent's class.
// parentPanel.js
import { LightningElement } from 'lwc';
export default class ParentPanel extends LightningElement {
total = 0;
handleCountChange(event) {
this.total = event.detail.count;
}
}Because total is a class field, reassigning it re-renders the parent template. The previous chapters on reactivity explain why.
The same thing in plain JavaScript
You can also attach a listener from JavaScript. This is useful when the element is created at runtime or when you need to remove the listener later.
// inside a component class
connectedCallback() {
this.addEventListener('countchange', this.handleCountChange.bind(this));
}The template syntax is preferred for child components that appear in your markup. It is shorter and the framework cleans it up for you.
How an event travels
An event has a path through the DOM. Two flags in the options object control how far it goes.
bubbles: iftrue, the event moves up through each ancestor after it fires on the target. The default isfalse.composed: iftrue, the event can cross a shadow DOM boundary. The default isfalse.
With the defaults (bubbles: false, composed: false), the event fires only on the host element of the child. A parent that has oncountchange on that child element in its own template receives it, because the listener is attached directly to the target. No bubbling is needed for this direct parent-to-child case.
That is why the example above works without any flags. It is also the safest default. The event does not leak to unrelated ancestors.
When you need bubbles
Suppose a grandparent wants to hear an event from a grandchild. With the defaults, the grandchild's event never reaches the grandparent. Setting bubbles: true lets the event move up through the ancestors inside the same shadow tree.
this.dispatchEvent(
new CustomEvent('itemselect', {
detail: { id: this.recordId },
bubbles: true
})
);Setting composed: true as well makes the event cross every shadow boundary. This exposes the event, and its target details, to every ancestor and to the page. Avoid this unless you have a specific reason. A better design is for each component to listen to its child and, if needed, dispatch a new event of its own. This is called re-dispatching, and it keeps each component's public surface small and explicit.
Event payloads
Put the data in detail. Keep these points in mind.
- Keep payloads small and plain. Send IDs, strings, numbers, or simple objects. A listener should not need to know the child's internals.
- Do not send mutable internal state. If
detailholds an object that the child also uses, the parent can change it and break the child. Send a copy instead. For example, use{ ...this.selection }or[...this.items]. - Treat
detailas read-only in the handler. It is data about something that already happened.
Preventing the default action
CustomEvent can be cancelable. If you set cancelable: true, listeners can call event.preventDefault(), and dispatchEvent returns false in that case.
const proceed = this.dispatchEvent(
new CustomEvent('beforeclose', { cancelable: true })
);
if (proceed) {
this.close();
}Use this sparingly. It lets a parent veto an action in the child, which is a form of coupling.
Common errors
- Uppercase or hyphenated event name. Naming an event
countChangeorcount-changemakes theonattribute in the parent template fail to match. Usecountchange. - Reading data from the wrong place. Payload data is in
event.detail, not directly onevent. - Expecting a grandparent to hear the event. Without
bubbles: true, only listeners on the child host element run. - Using
event.targetto identify the child. Because of shadow DOM, the target seen by an outer listener can be retargeted to the host element. Put the identifier you need indetail. - Mutating
detailobjects. Share copies, not live references. - Dispatching before the component is connected. Dispatching in the constructor is not allowed in LWC. Dispatch from
connectedCallbackor later, such as in a handler.
Standard versus LWC
Everything in the JavaScript event code is standard: CustomEvent, detail, bubbles, composed, cancelable, dispatchEvent, and addEventListener. The only LWC addition in this chapter is the onname={handler} syntax in templates, which the compiler turns into a standard listener. If you remove LWC, the same events still work in any web component.
Exercise
A grandchild component dispatches new CustomEvent('itemselect', { detail: { id: 7 } }). The parent component's template includes the grandchild's parent, and the grandparent places onitemselect={handleSelect} on that parent element. The handler never runs. Give two ways to fix this, and say which one you prefer and why.
Show answer
With the default flags the event fires only on the grandchild's host element, so a listener on the grandparent's element for the middle component never sees it. Fix 1: set bubbles: true on the event so it travels up through ancestors in the same shadow tree (it may also need composed: true if a shadow boundary lies between). Fix 2: have the middle component listen for itemselect on the grandchild and dispatch its own itemselect event with the same detail. The second is preferable because each component keeps a small, explicit public interface and the event does not leak to unrelated listeners.
Exercise
Why is onCountChange={handler} wrong in an LWC template for an event dispatched as new CustomEvent('countChange'), and what should you change?
Show answer
The template listener syntax is on plus a lowercase event name, and uppercase letters do not match. Rename the event to countchange in the CustomEvent constructor and use oncountchange={handler} in the template.