Child-to-Parent Communication with CustomEvent
By the end of this lesson, you'll be able to:
- Construct and dispatch a CustomEvent with a data payload
- Listen for a custom event correctly in a parent component
- Apply the correct naming convention for multi-word custom events
Prerequisites: "Public Properties and Public Methods"
Constructing and Dispatching a CustomEvent
// contactListItem.js
handleSelect() {
const selectEvent = new CustomEvent('select', {
detail: this.contact.Id,
});
this.dispatchEvent(selectEvent);
}
The event's detail property carries whatever data the parent needs — here, the ID of the selected contact.
Listening in the Parent
<!-- parent's template -->
<c-contact-list-item onselect={handleContactSelect}></c-contact-list-item>
// parent's JS
handleContactSelect(event) {
const selectedId = event.detail;
// ... do something with selectedId
}
The parent listens using on followed by the event name, in the same onclick-style pattern from Module 3 — because CustomEvent genuinely IS built on the same native Event foundation.
Naming Multi-Word Events
// Event name must be lowercase, no camelCase:
new CustomEvent('itemselected', { detail: this.itemId }); // correct
new CustomEvent('itemSelected', { detail: this.itemId }); // AVOID — will not bind reliably as onitemSelected
Custom event names must be entirely lowercase — LWC does not translate camelCase event names the way it translates attribute names. This is a genuinely common real bug: a developer expects onitemSelected to work, and it silently doesn't.
Why This Matters in Real Projects
This is the standard mechanism for any child that needs to tell its parent something happened — a row was clicked, a value changed, an action completed. It's also the exact foundation the module's Project lesson builds a real interaction on.
Exercise
Write the code to dispatch a CustomEvent named "delete" carrying a record's id in its detail.
Show hint
Use new CustomEvent(...) and this.dispatchEvent(...).
Exercise
Challenge: a developer names their event "itemSelected" (camelCase) and listens for onitemSelected in the parent, but it never fires. Explain the bug and the fix.
Show hint
Recall the required casing for custom event names.
Child-to-Parent Communication with CustomEvent Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
The full depth on child-to-parent communication — building on Module 3's intro with the constructor options and naming rules that matter once events carry real data.