Sub topic 5
Sending data with the detail property
A custom event that only says "something happened" is often not enough. The parent usually needs to know which tile was clicked, what value was typed, or which row was removed. The detail property of a CustomEvent carries that information.
This chapter assumes you can write a basic LWC class and template, expose properties with @api, and nest one component inside another. It also assumes you have seen a child call this.dispatchEvent(new CustomEvent(...)). Here the focus is on what goes into detail, what comes out on the other side, and which mistakes cause bugs.
What detail is
detail is a property of the CustomEvent interface, which is a standard web API and not specific to LWC. You set it through the second argument of the constructor:
const event = new CustomEvent('productselected', {
detail: { productId: 'p1' }
});Three facts about detail shape everything else in this chapter.
- It can hold any JavaScript value: a string, number, boolean, array, plain object, or
null. - It is optional. If you leave it out,
event.detailisnull. - It is read-only on the event. You cannot reassign
event.detail, but if it holds an object, the contents of that object can still be changed.
The last point is the source of most bugs, and a later section returns to it.
Choosing a shape for the payload
You can send one value or a structured object. Both work. Choose based on how likely the payload is to grow.
A single primitive
For a one-value event, you can pass the value directly:
// searchBox.js
import { LightningElement } from 'lwc';
export default class SearchBox extends LightningElement {
handleChange(event) {
this.dispatchEvent(
new CustomEvent('searchchange', {
detail: event.target.value
})
);
}
}The parent reads it as event.detail, which is the string itself. This is short, but it has a cost. If you later need to add a second value, such as whether the user pressed Enter, you must change the type from a string to an object. Every parent that listens will break.
A plain object with named keys
The more common choice is an object, even for one value:
detail: { value: event.target.value }Adding a field later, such as detail: { value, submitted: true }, does not break existing handlers that only read detail.value. Named keys also make handlers self-documenting: event.detail.productId tells the reader more than event.detail.
| Payload style | Example | Good for | Risk |
|---|---|---|---|
| Primitive | `detail: 'p1'` | A single stable value | Changing the type later breaks every listener |
| Plain object | `detail: { productId: 'p1' }` | Most events | Shared reference, so listeners can mutate it |
| No detail | omitted, so `null` | Pure signals such as "closed" | Handler must not read `event.detail.x` |
The no-detail case deserves a warning. If a handler written for an event with detail is attached to an event without it, event.detail.productId throws a TypeError, because event.detail is null.
Reading detail in the parent
The parent handler receives the event object as its first argument. The payload is at event.detail. Destructuring keeps handlers short:
// productList.js
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
selectedId;
handleProductSelected(event) {
const { productId } = event.detail;
this.selectedId = productId;
}
}The template attaches the handler with the on prefix and the event name. The child dispatches productselected, so the attribute is onproductselected:
<!-- productList.html -->
<template>
<c-product-tile
product-id="p1"
name="Desk"
onproductselected={handleProductSelected}>
</c-product-tile>
<p>Selected: {selectedId}</p>
</template>Assigning to selectedId re-renders the paragraph, because class fields are reactive in LWC. Nothing about detail needs special handling for that.
The full path of one value looks like this:
The payload is shared by reference
When dispatchEvent runs, the browser calls every matching listener with the same event object. That event holds one detail object. It is not copied for each listener. If the object is changed anywhere, every holder of that reference sees the change.
This matters in two situations.
- A listener mutates the payload. If a parent handler or a bubbling intermediate handler does
event.detail.items.push(x), the child's own array may change too, if the child put its own array intodetail. - The child keeps using what it sent. The child may update the same object later and surprise a parent that stored the reference.
The fix is to send a copy that no one else owns. For flat objects, a spread copy is enough:
// cartItem.js
import { LightningElement, api } from 'lwc';
export default class CartItem extends LightningElement {
@api item = { id: 'i1', name: 'Desk', quantity: 1 };
handleRemove() {
this.dispatchEvent(
new CustomEvent('itemremove', {
detail: { ...this.item }
})
);
}
}For nested data, a spread copies only the top level. Nested objects and arrays are still shared. Copy deeper levels too, or use a deep clone when the data is plain JSON-compatible values:
detail: JSON.parse(JSON.stringify(this.item))JSON.parse(JSON.stringify(...)) drops functions and undefined values, and it turns Date objects into strings. It is a reasonable default for record-like data, and a poor one for anything else.
A more fundamental way to avoid this problem is to send less. Often an identifier is enough, and the parent can look up the rest from data it already has.
Read-only data and errors in handlers
Data your component receives from outside is often read-only. A value passed through an @api property from a parent, or returned from @wire, may be wrapped in a read-only proxy. If you forward such an object in detail and a parent handler tries to change it, the assignment fails. The error usually points at the handler rather than at the place that created the payload, which makes it confusing.
Copying the object before dispatching, as shown above, gives the listener a normal, writable object. It also separates the listener from the original source.
The reverse direction is also worth knowing. A parent handler should treat event.detail as input to read, not as state to keep. If the parent needs to store the payload, assign a copy or just the fields it needs:
handleItemRemove(event) {
const { id, name } = event.detail;
this.removedItems = [...this.removedItems, { id, name }];
}Here the parent builds its own object, so later changes to the child's data cannot leak into removedItems.
What not to put in detail
Keep the payload to plain data. Avoid these:
- Functions. They tie the parent to the child's internals, and they do not survive some boundaries.
- DOM nodes or references to other components. The parent then depends on the child's template structure.
- Large objects "just in case". Every extra field becomes part of the event's contract. Once parents depend on it, you cannot remove it safely.
- Sensitive values that the parent has no reason to see. Events can bubble to places you did not plan for (see the chapter on propagation).
A useful test: could you describe the payload in one sentence, and could you write it as JSON? If not, it is probably too much.
Documenting the contract
Since JavaScript does not enforce detail, the shape exists only by convention. Write it down next to the dispatch code. A short comment is enough:
// Event: itemremove
// detail: { id: string, name: string }
// Fired when the user clicks Remove. The payload is a copy.
this.dispatchEvent(
new CustomEvent('itemremove', {
detail: { id: this.item.id, name: this.item.name }
})
);When several events in an application share a pattern, a small helper keeps the code consistent:
// eventHelpers.js
export function dispatchDetail(component, name, detail) {
component.dispatchEvent(new CustomEvent(name, { detail }));
}A component calls dispatchDetail(this, 'itemremove', { id: this.item.id }). Use a helper like this only if it removes real repetition. For a handful of events, the plain dispatchEvent call is easier to read.
Testing the payload
A Jest test should assert the payload and not only that the event fired. A handler that is called with the wrong detail is a real bug, and a test that only counts calls misses it.
// productTile.test.js
import { createElement } from 'lwc';
import ProductTile from 'c/productTile';
describe('c-product-tile', () => {
it('dispatches productselected with the product id', () => {
const element = createElement('c-product-tile', { is: ProductTile });
element.productId = 'p1';
document.body.appendChild(element);
const handler = jest.fn();
element.addEventListener('productselected', handler);
element.shadowRoot.querySelector('button').click();
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0].detail.productId).toBe('p1');
});
});handler.mock.calls[0][0] is the first argument of the first call, which is the event object. Use toEqual when the payload has several fields:
expect(handler.mock.calls[0][0].detail).toEqual({ productId: 'p1' });toEqual compares contents, so it also catches an extra field that sneaks into the payload.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `TypeError: Cannot read properties of null (reading 'productId')` | The event was dispatched without `detail`, or the handler is attached to the wrong event | Pass `detail` in the constructor, and check the event name |
| `event.detail` is `undefined` or empty | The payload was put at the top level of the options object instead of under `detail` | Use `{ detail: { ... } }` |
| Changing a value in the parent also changes it in the child | The child sent a reference to its own object | Send a copy or a primitive |
| Assigning to a property of `event.detail` throws | The object came from a read-only source such as `@wire` or an `@api` value | Copy it before dispatching, or copy it in the handler |
| A `Date` arrives as a string | A JSON clone was used | Send a timestamp number and rebuild the date in the parent |
The second row is a frequent slip. This code looks reasonable but sends no payload:
new CustomEvent('productselected', { productId: this.productId });The constructor ignores unknown option keys, so event.detail is null. The correct form wraps the data in detail.
Summary of rules
- Put the payload under the
detailkey of the constructor options. - Prefer a plain object with named keys, so fields can be added later.
- Send copies or identifiers, never an object the child will keep changing.
- Keep the payload small, plain, and documented.
- Assert the
detailvalue in Jest tests.
Exercise
A child component dispatches this event: new CustomEvent('rowedit', { id: this.rowId, value: this.value }). The parent handler does const { id, value } = event.detail; and throws a TypeError. Explain the cause, then rewrite the dispatch so the parent handler works and the payload is safe from later changes to a this.row object that also contains nested tags array data.
Show answer
The data is placed at the top level of the options object. CustomEvent only reads the detail key, so event.detail is null, and destructuring null throws a TypeError. The fix is to wrap the data under detail. To protect against shared references, send only the needed fields and copy the nested array: new CustomEvent('rowedit', { detail: { id: this.rowId, value: this.value, tags: [...this.row.tags] } }). The spread copies the array, so a parent that changes detail.tags does not change the child's row.tags. If the tags contained nested objects, they would need a deeper copy.