Sub topic 13
Returning data to the parent with custom events
This chapter assumes you can build a basic Lightning web component and that you know how a parent sets a child's @api properties. It also assumes you are comfortable with JavaScript classes, arrow functions, and the spread syntax.
Data flows down from parent to child through public properties. A child cannot change those values, so it needs another way to tell the parent that something happened. That mechanism is the custom event. The child dispatches an event, and the parent listens for it and decides what to do.
Why events complete the one-way data flow
A child receives values from its parent as read-only. If the child needs to report a user action, such as a click, a selection, or a finished edit, it sends a message upward. The parent then updates its own data. The new data flows back down through the same public properties.
This gives a loop with a clear owner for each piece of data.
The child never edits the parent's data. It only reports what the user did.
Creating and dispatching an event
You create an event with the CustomEvent constructor and send it with this.dispatchEvent(). The constructor takes an event name and an optional options object.
// taskCard.js (child)
import { LightningElement, api } from 'lwc';
export default class TaskCard extends LightningElement {
@api taskId;
@api heading;
handleComplete() {
const completeEvent = new CustomEvent('complete', {
detail: { taskId: this.taskId }
});
this.dispatchEvent(completeEvent);
}
}<!-- taskCard.html (child) -->
<template>
<article>
<h3>{heading}</h3>
<button onclick={handleComplete}>Mark complete</button>
</article>
</template>The detail property carries the payload. Put whatever the parent needs inside it. Keep the payload small and specific, such as an ID or a new value, and not a reference to the whole component state.
Event naming rules
Follow these rules for the event name:
- Use only lowercase letters.
- Do not use spaces, hyphens, or uppercase letters. Use a single word where you can, or join words together, such as
taskcomplete. - Do not start the name with
on. The parent adds that prefix itself in the markup. - Do not reuse the names of standard DOM events such as
clickorchangeunless you intend to mimic them.
The name must be lowercase because the parent attaches the listener as an HTML attribute, and HTML attribute names are case-insensitive.
Listening in the parent
The parent attaches a handler in its template. The attribute is on followed by the event name.
<!-- taskBoard.html (parent) -->
<template>
<c-task-card
task-id="t-100"
heading="Write documentation"
oncomplete={handleTaskComplete}>
</c-task-card>
<p>Completed: {completedCount}</p>
</template>// taskBoard.js (parent)
import { LightningElement } from 'lwc';
export default class TaskBoard extends LightningElement {
completedCount = 0;
handleTaskComplete(event) {
const { taskId } = event.detail;
console.log('Completed task', taskId);
this.completedCount += 1;
}
}The handler receives the event object. Read the payload from event.detail. Because completedCount is a class field, changing it re-renders the template.
Note how the attribute oncomplete is built. The event name is complete, and the parent adds the on prefix. If the event were named taskcomplete, the attribute would be ontaskcomplete.
Events inside a list
When the parent renders many children with for:each, all of them can share one handler. The child includes an identifier in detail, and the parent uses it to find the right item.
<!-- taskBoard.html (parent) -->
<template>
<template for:each={tasks} for:item="task">
<c-task-card
key={task.id}
task-id={task.id}
heading={task.name}
oncomplete={handleTaskComplete}>
</c-task-card>
</template>
</template>// taskBoard.js (parent)
import { LightningElement } from 'lwc';
export default class TaskBoard extends LightningElement {
tasks = [
{ id: 't-1', name: 'Write documentation', done: false },
{ id: 't-2', name: 'Review pull request', done: false }
];
handleTaskComplete(event) {
const id = event.detail.taskId;
this.tasks = this.tasks.map((task) =>
task.id === id ? { ...task, done: true } : task
);
}
}The handler builds a new array with map and assigns it to this.tasks. It does not modify the old array in place. This keeps the parent as the single owner of the data, and the updated list flows back down to each child.
Event options: bubbles and composed
By default, a custom event does not bubble. Only the element that dispatched it, and the parent's listener attached directly to that element, will see it. Two options change this behavior.
| Option | Default | Effect |
|---|---|---|
| `bubbles` | `false` | The event travels up through the ancestors in the same DOM tree. |
| `composed` | `false` | The event can cross the shadow boundary into the parent's tree and beyond. |
In most cases you should keep both at false. A listener on the child's tag in the parent's template works with the defaults. Turning on bubbles and composed lets any ancestor catch the event, which couples distant components together and makes the code hard to follow.
If a grandparent needs the data, the usual pattern is for the parent to catch the child's event and then dispatch its own event upward. Each component talks only to its direct neighbor.
Designing the payload
The detail value should follow these guidelines:
- Send primitive values or plain objects. They are easy to read and to test.
- Do not send a reference to a large object that the parent owns. The parent already has it.
- Do not expect the child to hold the final copy of the data. The parent decides what to do with the event.
- Do not put functions or component references in
detail.
Objects passed in detail may be shared with the receiver. If the parent might change the object, or the child will reuse it, make a copy first.
// filterPanel.js (child)
import { LightningElement } from 'lwc';
export default class FilterPanel extends LightningElement {
selected = { status: 'open', owner: 'me' };
handleApply() {
this.dispatchEvent(
new CustomEvent('apply', {
detail: { ...this.selected }
})
);
}
}The spread syntax creates a shallow copy. The parent receives its own object, and later changes in the child's selected do not affect it.
Choosing between properties, methods, slots, and events
Each tool answers a different question. This table summarizes when to use each one.
| Need | Tool | Direction |
|---|---|---|
| Give the child a value to display or use | `@api` property | Parent to child |
| Ask the child to perform an action | `@api` method | Parent to child |
| Give the child markup to render | Slot | Parent to child |
| Report a user action or a new value | Custom event | Child to parent |
A common mistake is to try to make the child call a function the parent passes in as a property. Prefer an event. It keeps the child independent, because the child does not need to know anything about who is listening.
Common pitfalls with events
- Uppercase or hyphenated names. An event named
taskCompletedoes not match the attributeontaskCompletereliably. Use lowercase, such astaskcomplete. - Adding
onin the event name. If you dispatchoncomplete, the parent must writeononcomplete. Dispatchcompleteinstead. - Reading data from the wrong place. The payload is in
event.detail, not on the event itself. - Modifying the parent's array in place. Assign a new array so the template re-renders and the data stays predictable.
- Dispatching in the constructor. The component is not yet attached, so no parent is listening. Dispatch in response to a user action or in
connectedCallbackonly when the parent is ready for it. - Making events bubble by default. This leads to unexpected listeners and name collisions.
Putting it together
The following example combines a property, a setter, and an event. The child shows a rating, the parent supplies the starting value, and the child reports the new rating when the user picks one.
// ratingPicker.js (child)
import { LightningElement, api } from 'lwc';
export default class RatingPicker extends LightningElement {
_value = 0;
@api
get value() {
return this._value;
}
set value(newValue) {
const number = Number(newValue);
this._value = Number.isFinite(number) ? number : 0;
}
get options() {
return [1, 2, 3, 4, 5].map((n) => ({
n,
label: String(n),
selected: n === this._value
}));
}
handlePick(event) {
const picked = Number(event.target.dataset.rating);
this._value = picked;
this.dispatchEvent(
new CustomEvent('ratingchange', { detail: { value: picked } })
);
}
}<!-- ratingPicker.html (child) -->
<template>
<template for:each={options} for:item="option">
<button
key={option.n}
data-rating={option.n}
aria-pressed={option.selected}
onclick={handlePick}>
{option.label}
</button>
</template>
</template><!-- reviewForm.html (parent) -->
<template>
<c-rating-picker value={rating} onratingchange={handleRatingChange}></c-rating-picker>
<p>Current rating: {rating}</p>
</template>// reviewForm.js (parent)
import { LightningElement } from 'lwc';
export default class ReviewForm extends LightningElement {
rating = 3;
handleRatingChange(event) {
this.rating = event.detail.value;
}
}The child keeps its own _value so the interface responds right away. The parent stores the same number in rating. When the parent sets rating, the setter runs again and stays in sync. The child never writes to value from outside the setter, and the parent only learns of changes through the event.
Exercises
Exercise
A child component dispatches new CustomEvent('itemSelected', { detail: { id: 5 } }). The parent uses onitemSelected={handleSelect}. The handler never runs. What should you change, and why?
Show answer
Rename the event to all lowercase, such as itemselected, and use onitemselected={handleSelect} in the parent. Event names should be lowercase with no hyphens because the parent attaches the listener as an HTML attribute, and attribute names are case-insensitive.
Exercise
A parent handler receives an event from a child. Where is the data the child sent, and how would you read an id value from it?
Show answer
The data is in event.detail. Read it with event.detail.id, or destructure it with const { id } = event.detail;.
Exercise
A grandparent needs to know when a grandchild dispatches a select event. The grandchild event uses the defaults. What is the recommended way to get the data to the grandparent without setting bubbles and composed?
Show answer
The parent listens for the grandchild's event, then dispatches its own custom event with the needed data in detail. The grandparent listens to the parent. Each component talks only to its direct neighbor, which keeps the contract small and clear.