How do child-to-parent communication channels work in LWC using Custom Events?
Answer
Basics: A child should not reach into its parent. Instead it announces that something happened ("item selected") with data, and whoever contains it decides what to do. This keeps components reusable.
How it works:
- In the child, create
new CustomEvent('itemselected', { detail: { id } })and callthis.dispatchEvent(evt). - In the parent template, attach
onitemselected={handleSelect}to the child tag. - The handler receives the event; read
event.detail. - Options:
bubbles(travels up the DOM tree),composed(crosses shadow boundaries). Both default to false, so a plain event is seen only by a listener on the child element itself. - Imperative listening is possible with
addEventListeneronthis.templateor on an element reference.
Advanced / deep dive: Event names should be lowercase, no spaces, and avoid uppercase letters and hyphens; underscores are acceptable; do not prefix with on. Choose the narrowest propagation: non-bubbling for direct parent, bubbling without composed for ancestors within one shadow tree, and both only when a distant container must hear it, because composed bubbling leaks across component boundaries and complicates reuse. detail should carry immutable, serializable data; a parent mutating a shared object would affect the child. For sibling or unrelated components use Lightning Message Service or a pub/sub module instead of bubbling hacks. For forms, standard events such as change from lightning-input follow the same mechanism and expose event.target.value. A parent can also call event.stopPropagation() to prevent further travel. Events are synchronous, so handlers run in the dispatch call.