Sub topic 9
Bubbling and crossing shadow boundaries with bubbles and composed
This chapter assumes you can already create a CustomEvent, dispatch it from a child with this.dispatchEvent, and handle it in the parent with an on<eventname> attribute. It also assumes you know that each LWC renders inside its own shadow tree. Here you will learn what the bubbles and composed options change, which components receive an event under each combination, and how to choose the narrowest setting that works.
Why the defaults work for the basic case
A CustomEvent is created with both options set to false unless you say otherwise:
new CustomEvent('productselected', { detail: { productId: 'p1' } });
// bubbles: false, composed: falseWhen the child calls this.dispatchEvent(...), the event fires on the child's host element. That is the <c-product-tile> element in the parent's template. A handler attached directly to that element, such as onproductselected={handleProductSelected}, runs because the host element is the event's target. The event does not need to travel anywhere.
This is why the basic child-to-parent pattern needs neither option. The two options only matter when something other than the host element itself needs to hear the event.
What each option controls
bubbles controls whether the event travels upward from the target to its ancestors, one parent element at a time. Without it, only listeners on the target (and capture-phase listeners above it) run.
composed controls whether the event may cross a shadow root. A shadow root is the boundary between a component's template and the element that hosts that component. Without composed, an event stops at the edge of the shadow tree where it started.
The two options work together. composed only lets a bubbling event leave a shadow tree, so it has little use without bubbles.
| bubbles | composed | Who can receive the event | Typical use |
|---|---|---|---|
| false | false | Listeners on the dispatching host element only | Default. Parent listens on the child tag |
| true | false | The host, plus ancestors inside the same shadow tree as the host | Wrapper elements or `this.template` in the parent |
| true | true | Every ancestor, across all shadow boundaries, up to `document` | Rare. Page-wide signals |
| false | true | Not recommended | Subtle behavior that surprises most developers |
Tracing the event path
Consider three nested components. c-app contains c-product-list, which contains c-product-tile. Each arrow below means "contains".
There are two shadow boundaries in this chain. One sits between c-app's host and its template. The other sits between c-product-list's host and its template. The tile's host element belongs to the c-product-list shadow tree, because c-product-list wrote the <c-product-tile> tag in its template.
Now follow the event as the tile dispatches it:
- With
bubbles: false, only the tile host's own listeners run. The wrapper div never hears the event. - With
bubbles: trueandcomposed: false, the event rises to the wrapper div and any other element in thec-product-listtemplate. It stops at thec-product-listshadow root. Thec-product-listhost and everything above it never see it. - With
bubbles: trueandcomposed: true, the event also passes through the shadow root, reaches thec-product-listhost, the div inc-app, and continues todocument.
Using bubbles for event delegation
The most common reason to set bubbles: true is to put one listener on a wrapper instead of one on every child. Here is the tile, dispatching a bubbling event:
// productTile.js
import { LightningElement, api } from 'lwc';
export default class ProductTile extends LightningElement {
@api productId;
@api name;
handleClick() {
this.dispatchEvent(
new CustomEvent('productselected', {
detail: { productId: this.productId },
bubbles: true
})
);
}
}The parent template listens once on a container that holds many tiles:
<!-- productList.html -->
<template>
<div class="grid" onproductselected={handleGridSelected}>
<c-product-tile product-id="p1" name="Desk"></c-product-tile>
<c-product-tile product-id="p2" name="Lamp"></c-product-tile>
</div>
<p>Selected: {selectedName} ({selectedId})</p>
</template>The handler uses event.target to learn which tile fired:
// productList.js
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
selectedId;
selectedName;
handleGridSelected(event) {
this.selectedId = event.detail.productId;
this.selectedName = event.target.name;
}
}event.target is the <c-product-tile> element, so reading its public name property works. This pays off when tiles are rendered in a loop, since you attach the handler once on the container.
The order of handlers follows the path. A handler on the <c-product-tile> tag itself runs first, then the handler on the div. The same event object reaches both, so a handler can call event.stopPropagation() to keep the event from rising further.
Listening on the whole template
A parent can also catch bubbling events from anywhere in its own template without a wrapper element. It does this by listening on this.template:
// productList.js (alternative)
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
constructor() {
super();
this.template.addEventListener('productselected', (event) => {
console.log('Selected', event.detail.productId);
});
}
}This works only because the event bubbles. Without bubbles: true, the event fires on the tile host and never rises to the template root.
Using composed to cross shadow boundaries
Suppose c-app needs to hear the tile's event directly, with c-product-list playing no part. Setting both options makes that possible:
this.dispatchEvent(
new CustomEvent('productselected', {
detail: { productId: this.productId },
bubbles: true,
composed: true
})
);<!-- app.html -->
<template>
<c-product-list onproductselected={handleSelected}></c-product-list>
</template>// app.js
import { LightningElement } from 'lwc';
export default class App extends LightningElement {
handleSelected(event) {
console.log(event.target.tagName); // C-PRODUCT-LIST
console.log(event.detail.productId);
}
}The logged tag name is C-PRODUCT-LIST, not the tile. The browser retargets event.target so that code outside a shadow tree never receives a reference to an element inside it. From c-app's point of view, the event came from c-product-list. This keeps component internals private, but it means event.target cannot tell c-app which tile fired. Put what the listener needs into detail.
If you need to inspect the real route, event.composedPath() returns the list of nodes the event passes through. Closed shadow trees are omitted, and the list is limited for code outside a tree, so treat it as a debugging aid and not as application logic.
Why composed events are usually a mistake
A composed, bubbling event is visible to every ancestor of the dispatching component, including components you did not write. That has three costs:
- Name collisions. Any ancestor listening for
productselectedreceives it. If two unrelated components use the same name, one may react to the other's events. - Broken encapsulation. The event's existence becomes part of your component's public surface. Parents of parents may start depending on it, and renaming it breaks them.
- Unclear data flow. A reader of
c-appcannot see from its template which descendant produces the event.
A cleaner alternative: re-dispatch from the middle component
Instead of one composed event that travels the whole tree, have each layer handle the event and send its own. The middle component translates the child's event into one that belongs to its own API:
// productList.js
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
handleProductSelected(event) {
event.stopPropagation();
this.dispatchEvent(
new CustomEvent('itemselected', {
detail: { id: event.detail.productId }
})
);
}
}c-app then listens with onitemselected. The tile and the list can change independently, because c-app knows only the list's contract. The cost is a little more code in the middle layer. In a deep hierarchy that cost grows, and that is the point where the alternatives in a later chapter, such as a shared service module or Lightning Message Service, become worth considering.
Slotted content
Components often pass child elements into a container through a <slot>. The slotted element still belongs to the shadow tree of the component that wrote it in its template, not the container's. For event routing, the event still rises through the <slot> element and the container's host as part of the flattened tree. As a result, an element in the container's template that wraps the slot can receive a bubbling event from slotted content, even when composed is false. If your handler fires in a place you did not expect, check whether a slot is involved before you change composed.
Choosing the options
Work from the narrowest setting outward, and stop at the first one that satisfies the need:
- Parent listens on the child's tag. Use neither option.
- A wrapper element or
this.templatein the parent must catch events from many children. Usebubbles: true. - A component that is not a direct parent must hear the event. Prefer re-dispatching. Use
bubbles: true, composed: trueonly for a signal that is designed to be page-wide, with a distinctive name.
Testing the flags
You can confirm what a component dispatches by capturing the event and checking its flags. This test belongs next to the earlier productTile.test.js example.
// productTile.propagation.test.js
import { createElement } from 'lwc';
import ProductTile from 'c/productTile';
describe('c-product-tile propagation', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('dispatches a bubbling event', () => {
const element = createElement('c-product-tile', { is: ProductTile });
element.productId = 'p1';
document.body.appendChild(element);
const handler = jest.fn();
document.body.addEventListener('productselected', handler);
element.shadowRoot.querySelector('button').click();
expect(handler).toHaveBeenCalledTimes(1);
const event = handler.mock.calls[0][0];
expect(event.bubbles).toBe(true);
expect(event.composed).toBe(false);
document.body.removeEventListener('productselected', handler);
});
});The listener sits on document.body, which is an ancestor of the host. It runs only if the event bubbles. Checking event.composed directly is more reliable than trying to detect it through routing, because the tile's host is in the light DOM of body, so a composed event and a non-composed one both reach it. To verify real shadow crossing, mount a small parent component in the test and listen on a grandparent.
Common errors
- Handler on a wrapper never fires. The event does not bubble. Add
bubbles: truein the child. - Handler on the grandparent never fires. The event is not composed, or an intermediate component called
stopPropagation(). - Handler fires twice. The event bubbles, and listeners exist on both the child tag and a wrapper. Remove one, or stop propagation.
event.targetis not the element you expected. Retargeting replaced it. Read identifying data fromevent.detail.- Unrelated components react to the event. A composed event with a generic name is leaking. Rename it or stop composing.
Exercise
A c-tile dispatches new CustomEvent('tileclick', { detail: { id: 7 }, bubbles: true }). It sits inside a <div onitemclick...> wrapper in c-list's template. c-list sits inside c-page, which has <c-list ontileclick={handle}>. Does c-page's handler run, and what would you change so that c-page receives an event from the list without exposing the tile?
Show answer
No. The event bubbles within c-list's shadow tree but is not composed, so it stops at c-list's shadow root and never reaches the c-list host. (Also note the wrapper's attribute should be ontileclick, not onitemclick, to match the event name.) To get a signal to c-page without composing the event, handle tileclick in c-list, call event.stopPropagation(), and dispatch a new CustomEvent such as itemselected on c-list's host with the data c-page needs in detail. c-page then listens with onitemselected.
Exercise
Why does event.target in c-app's handler show C-PRODUCT-LIST even though a c-product-tile dispatched the event?
Show answer
The browser retargets event.target when an event crosses a shadow boundary. Code outside a shadow tree sees the host element of that tree as the target, not an element inside it. The tile lives inside c-product-list's shadow tree, so c-app sees c-product-list. Anything c-app needs to know about the tile must be sent in event.detail.