Sub topic 7
Reading event.detail in the handler
This chapter assumes you can write a basic LWC (an HTML template plus a JavaScript class) and expose properties with @api. It also assumes you have already seen how a child dispatches a CustomEvent and how a parent attaches onproductselected={handleProductSelected} in its template. Here the focus is the other end of the wire: what the handler receives, how to read the payload safely, and which mistakes are common.
What the handler receives
When the child calls dispatchEvent, the browser creates an event object and passes it as the first argument to every listener. In an LWC template handler, the engine calls your method with that object and with this bound to the parent component. You don't write this.handleProductSelected.bind(this), and you don't write parentheses in the template.
<c-product-tile onproductselected={handleProductSelected}></c-product-tile>The handler is an ordinary class method:
handleProductSelected(event) {
console.log(event.type); // "productselected"
console.log(event.detail); // whatever the child put in detail
}The object is a CustomEvent, which extends the standard DOM Event. These are the properties you use most often:
| Property | What it holds | Typical use in a handler |
|---|---|---|
| `detail` | The payload the child passed in the `CustomEvent` constructor. | Reading the data the child wants to send. |
| `type` | The event name, such as `productselected`. | Sharing one handler between several event names. |
| `target` | The element that dispatched the event, as seen from the parent's template. | Rarely needed. Prefer putting data in `detail`. |
| `currentTarget` | The element the handler is attached to. | Telling apart handlers on a wrapper element. |
| `bubbles`, `composed` | The propagation flags set by the child. | Debugging why an event arrives or does not arrive. |
detail is the only property the child controls directly. Everything else is set by the DOM or by the dispatch options.
Reading the payload
The child decides the shape of detail. The parent must read it with the same shape. Suppose the tile sends the id and the display name:
// 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, name: this.name }
})
);
}
}The parent reads the fields through event.detail:
// productList.js
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
selectedId;
selectedName;
handleProductSelected(event) {
this.selectedId = event.detail.productId;
this.selectedName = event.detail.name;
}
}Assigning to class fields re-renders the template, because LWC fields are reactive. The template then shows the new values:
<!-- productList.html -->
<template>
<c-product-tile
product-id="p1"
name="Desk"
onproductselected={handleProductSelected}>
</c-product-tile>
<p>Selected: {selectedName} ({selectedId})</p>
</template>Note the naming difference. The attribute product-id in the template maps to the productId property in JavaScript. The keys inside detail are plain JavaScript object keys, so they keep the exact spelling the child used. The handler reads event.detail.productId, not event.detail['product-id'].
Destructuring and defaults
When the payload has several fields, destructuring keeps the handler short:
handleProductSelected(event) {
const { productId, name } = event.detail;
this.selectedId = productId;
this.selectedName = name;
}If the child may omit fields, add defaults at the point where you read them:
handleProductSelected(event) {
const { productId, name = 'Unnamed product' } = event.detail ?? {};
this.selectedId = productId;
this.selectedName = name;
}The ?? {} guard matters because of a detail that surprises many developers: when the child dispatches without a detail option, event.detail is null, not undefined and not an empty object. Destructuring null throws a TypeError. The guard is only worth adding when the event can legitimately arrive without a payload, or when several children share one handler.
The handler runs when the event fires
The handler is a plain function that runs at the moment of dispatch. Dispatching is synchronous. When the child calls dispatchEvent, every listener runs to completion before the next line of the child's code executes. That has two consequences:
- The parent's handler can run before the child finishes the method that dispatched the event. Don't rely on the child's state being final inside the handler.
- A handler that throws an error doesn't stop the child. The browser reports the error, and
dispatchEventreturns normally.
Using one handler for many children
Lists are the common case. Several tiles share one handler, and the handler needs to know which tile fired. Put the identifying data in detail, as the child already does with productId. The parent does not have to inspect the DOM to find out.
<!-- productList.html -->
<template>
<template for:each={products} for:item="product">
<c-product-tile
key={product.id}
product-id={product.id}
name={product.name}
onproductselected={handleProductSelected}>
</c-product-tile>
</template>
<p>Selected: {selectedName}</p>
</template>// productList.js
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
selectedId;
selectedName;
products = [
{ id: 'p1', name: 'Desk' },
{ id: 'p2', name: 'Chair' },
{ id: 'p3', name: 'Lamp' }
];
handleProductSelected(event) {
this.selectedId = event.detail.productId;
this.selectedName = event.detail.name;
}
}Reading from detail keeps the parent independent of how the child is built. If you instead read event.target.dataset or event.target.productId, the parent depends on the child's internals, and a later change to the child can break it.
target and currentTarget
The two properties are easy to confuse. currentTarget is the element where the listener is attached. target is where the event originated. For a listener placed directly on <c-product-tile>, both point to the same host element.
They differ when the event bubbles to an ancestor. Suppose the child dispatches with bubbles: true and the parent wraps tiles in a div:
<div class="grid" onproductselected={handleProductSelected}>
<c-product-tile product-id="p1" name="Desk"></c-product-tile>
<c-product-tile product-id="p2" name="Chair"></c-product-tile>
</div>Inside the handler, event.currentTarget is the div, and event.target is the c-product-tile that fired. The engine retargets target so the parent only sees its own template's elements. It will never expose elements inside the child's shadow tree. Even then, detail is the better source of data.
Treat detail as read-only
The detail object is shared by reference. The child and every listener along the path see the same object. This leads to two rules.
- In the handler, don't modify
event.detail. Another listener may read it after you, and the framework may hand your component a read-only view of the object. Writing to it can throw an error or silently affect other code. - In the child, don't put live internal state in
detail. Build a new object for each dispatch.
When the parent needs to change what it received, copy first:
handleFiltersChanged(event) {
const filters = { ...event.detail }; // shallow copy
filters.page = 1;
this.filters = filters;
}A shallow copy protects only the top level. If detail holds nested objects or arrays, copy those too, for example with [...event.detail.ids], before changing them.
On the child side, send a fresh copy:
this.dispatchEvent(
new CustomEvent('selectionchange', {
detail: { ids: [...this.selectedIds] }
})
);Keep the payload to simple, serializable values: strings, numbers, booleans, plain objects, and arrays of those. Passing a whole record or a component reference works technically, but it ties the parent to the child's internals.
Common errors
- Reading the field from the event itself.
event.productIdisundefined. The data is underevent.detail. - Using the wrong spelling. The key in
detailmust match exactly, including case.event.detail.productIDreturnsundefinedwithout any error, so a typo shows up as a blank value on screen. - Destructuring a missing detail.
const { productId } = event.detailthrows whendetailisnull. Guard withevent.detail ?? {}if the payload is optional. - Calling the handler in the template.
onproductselected={handleProductSelected()}is not valid. Pass the method name only. - A handler name that doesn't match the event. The attribute is
onplus the event name in lowercase. An event namedproductSelectedcan't be listened to withonproductSelected, which is one reason event names should be lowercase. If the handler never runs, compare the event name and the attribute character by character. - Changing
detailin place. See the previous section. Copy it first. - Expecting a return value. The value a handler returns is ignored. A handler cannot send data back to the child through the event. To pass data down, set a public property on the child, or call a public method marked
@api.
Debugging a handler
Start with the cheapest checks:
- Add
console.log(event.type, event.detail)as the first line of the handler. If nothing prints, the problem is attaching the listener, not reading the payload. Check the event name, theonattribute, and whether the child is rendered at that moment. - If it prints but the value looks wrong, check what the child sends. Log inside the child right before
dispatchEvent. - In browser developer tools, a logged
detailmay appear as a proxy object. Expanding it, or usingJSON.stringify, shows the actual fields.
Exercise
A child dispatches new CustomEvent('quantitychange', { detail: { sku: 'A7', qty: 3 } }). The parent template has <c-qty-input onquantitychange={handleQty}></c-qty-input>. The handler is handleQty(event) { this.total = event.qty; }, and total stays undefined. What is wrong, and how do you fix it? Also write a version that destructures both fields and stays safe if detail is null.
Show answer
The handler reads event.qty, but custom data lives under event.detail. The fix is this.total = event.detail.qty;. A destructuring version that tolerates a missing payload is handleQty(event) { const { sku, qty } = event.detail ?? {}; this.total = qty; this.lastSku = sku; }. The ?? {} guard prevents a TypeError when detail is null.
Exercise
Why should a handler copy event.detail before changing it, and why is it better to put the product id in detail than to read it from event.target in the parent?
Show answer
The detail object is shared by reference with other listeners and can be a read-only view, so changing it in place can break other code or throw. A shallow copy such as { ...event.detail } is safe to edit. Reading the id from detail keeps the parent dependent only on the event contract. Reading it from event.target ties the parent to the child's internal properties, and target may also be retargeted when the event bubbles.