Sub topic 2
Creating a CustomEvent
This chapter covers the first half of sending a signal from child to parent: building the event object. Dispatching, naming, payloads and listening each get their own chapter. Here you learn what a CustomEvent is, what its constructor accepts, and the mistakes people make before the event ever leaves the child.
This chapter assumes you know basic JavaScript (classes, objects, ES modules), the structure of an LWC component (an HTML template plus a JavaScript class), how @api exposes public properties, and how to place one component inside another in a template.
Why a child needs to create an event
In LWC, data flows down through public properties. A parent sets @api properties on a child, and the child reads them. The child must not reach up and change the parent's state. When something happens inside the child, such as a click or a finished load, the child announces it with an event, and the parent decides what to do.
To announce something, the child first needs an event object. That object describes what happened and carries any data the parent needs. In LWC you build it with the standard browser class CustomEvent.
What a CustomEvent is
CustomEvent is a standard DOM class, not an LWC invention. It extends the base Event class and adds one thing: a detail property for carrying your own data. The same class works in any web page, so what you learn here applies outside Salesforce too.
You do not import it. It is a global, like document or Promise. Your component file needs no import line for it.
A CustomEvent is only an object until something dispatches it. Creating one does not notify anyone. The next chapter covers dispatchEvent.
The constructor
The constructor takes two arguments:
new CustomEvent(type, options);typeis a string that names the event, for example'productselected'. The parent listens for this exact string.optionsis an optional object, often called the init dictionary. It sets the payload and the event's behavior.
The options object accepts four keys that matter in LWC:
| Option | Default | What it controls |
|---|---|---|
| `detail` | `null` | The payload. Any value is allowed, but plain data is best. |
| `bubbles` | `false` | Whether the event travels up through ancestor elements. |
| `composed` | `false` | Whether the event can cross a shadow DOM boundary. |
| `cancelable` | `false` | Whether a listener can call `preventDefault()` and have the child see that. |
If you pass only a type, you get an event with no payload and the narrowest behavior:
const evt = new CustomEvent('refreshrequested');That is a complete, valid event. Many events need nothing more, such as "the user clicked close". Add options only when you have a reason.
A complete example
The following child component creates an event when a button is clicked. It builds the event in a local variable first, then dispatches it on the last line. Splitting the two steps makes it clear that they are separate.
// productTile.js
import { LightningElement, api } from 'lwc';
export default class ProductTile extends LightningElement {
@api productId;
@api name;
handleClick() {
const selectEvent = new CustomEvent('productselected', {
detail: { productId: this.productId }
});
this.dispatchEvent(selectEvent);
}
}<!-- productTile.html -->
<template>
<button onclick={handleClick}>{name}</button>
</template>Line by line:
handleClickis the handler for the nativeclickevent on the button. Native events come from the browser. Your custom event is a second, separate event that you create in response.new CustomEvent('productselected', { ... })builds the object. Nothing is sent yet.detailholds a small object with the product's ID. The parent will read it later.this.dispatchEvent(selectEvent)fires the event on the component's host element. This is the step that actually notifies the parent.
You can inspect an event in a browser console to see what the constructor produced:
const evt = new CustomEvent('productselected', {
detail: { productId: 'p1' }
});
console.log(evt.type); // "productselected"
console.log(evt.detail); // { productId: "p1" }
console.log(evt.bubbles); // false
console.log(evt.composed); // false
console.log(evt.cancelable); // falseThe last three values are the defaults. They explain behavior you will meet later, for instance why a listener on a distant ancestor never fires.
How the pieces fit together
The diagram shows where creation sits in the sequence. The constructor combines your type and options into an event object. Dispatching, which is a separate step, hands that object to the DOM.
CustomEvent versus Event
The base Event class also exists, and new Event('productselected') works. The difference is that a plain Event has no detail property. If you need to carry data, use CustomEvent.
const plain = new Event('productselected', { detail: { productId: 'p1' } });
console.log(plain.detail); // undefined: Event ignores the detail optionNo error is raised. The detail option is silently dropped, and the parent later reads undefined. This is a common source of "my payload is missing" bugs. In LWC, use CustomEvent by default, even for events with no payload. That keeps every event in your codebase the same shape.
Where to create events
Create the event at the moment you need to send it, usually inside an event handler or a method that responds to something. Two guidelines follow.
Create a fresh event each time. Do not build one event at class level and dispatch it repeatedly. The event object also holds state, such as whether a listener called preventDefault(), and sharing one across dispatches leads to confusing results. A CustomEvent is cheap to construct.
Do not dispatch from the constructor. The component's constructor() runs before the element is attached, and the parent has not yet attached its listeners. LWC also restricts what a constructor may do. If you need to announce that a component finished loading, use connectedCallback() or renderedCallback(), or fire the event after an asynchronous call finishes.
// statusBadge.js
import { LightningElement } from 'lwc';
export default class StatusBadge extends LightningElement {
connectedCallback() {
this.dispatchEvent(new CustomEvent('badgeready'));
}
}Here the event is created and dispatched inline in one expression. That is a fine pattern when the event is short, as in this example.
Choosing options deliberately
Each option widens the event's reach, so start narrow.
detail: pass data the parent needs and nothing more. A product ID is better than the whole product record. The chapter on payloads covers shape and safety in more detail.bubbles: leave itfalseunless an ancestor other than the direct parent must hear the event. Withfalse, only listeners on the child's host element itself, such as theonproductselectedattribute in the parent template, receive it.composed: leave itfalseunless the event must pass through shadow boundaries. Acomposedevent that also bubbles can reach listeners far outside the parent, which couples components in ways that are hard to untangle. Settingcomposed: trueis rarely needed.cancelable: set it totrueonly if the child will check the result ofdispatchEventand change behavior when a parent callspreventDefault().
// A cancelable event: the child proceeds only if no listener cancels it.
handleDelete() {
const deleteEvent = new CustomEvent('beforedelete', {
detail: { recordId: this.recordId },
cancelable: true
});
const proceed = this.dispatchEvent(deleteEvent);
if (proceed) {
this.deleteRecord();
}
}dispatchEvent returns false when a listener called preventDefault() on a cancelable event, and true otherwise. The cancelable option does nothing unless you use that return value. Setting it "just in case" adds a promise you do not keep.
Properties of the created event
Once constructed, these properties are fixed:
type,bubbles,composedandcancelableare read-only. You cannot change them after creation. If you picked the wrong value, create a new event.detailis a read-only reference. You cannot assign a different value toevt.detail, but if it points to an object, that object's contents can still change.
The second point matters. detail holds a reference, not a copy, so the child and every listener see the same object. A listener that edits it changes what the child sees, and later listeners see the edit too. If the child keeps using that object after dispatching, build a new object for the event:
// Pass a copy so a listener cannot change the child's internal state.
const evt = new CustomEvent('filterchange', {
detail: { ...this.filters }
});A spread copy is shallow. Nested objects are still shared. For simple payloads, prefer flat objects of strings, numbers and booleans.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Parent handler never runs | The event was created but `dispatchEvent` was never called | Call `this.dispatchEvent(evt)` |
| `event.detail` is `undefined` in the handler | Used `new Event(...)`, or put the payload outside the options object | Use `new CustomEvent(type, { detail: ... })` |
| `event.detail` is `null` | No `detail` option was given | Pass `detail` in the second argument |
| `dispatchEvent is not a function` | Called `dispatchEvent` without `this.` | Use `this.dispatchEvent(...)` |
| Listener on a distant ancestor never fires | `bubbles` and `composed` are `false` by default | Set the options only if you truly need that reach |
| Payload changes unexpectedly | The `detail` object was shared by reference | Pass a fresh or copied object |
The second row is easy to write by accident. Both of these lines look plausible, but only the first sets the payload:
new CustomEvent('productselected', { detail: { productId: 'p1' } }); // correct
new CustomEvent('productselected', { productId: 'p1' }); // payload lostIn the second line, productId is not a recognized option, so it is ignored and detail stays null.
Summary of decisions
When you write new CustomEvent(...), run through this short list:
- Is the type string correct? The parent must use the same one. Naming rules are in the next chapters.
- Does the parent need data? If yes, put it in
detail. If no, omit the options object. - Does anyone beyond the direct parent need it? If no, leave
bubblesandcomposedoff. - Will you act on a cancellation? If no, leave
cancelableoff. - Is
detaila copy or a simple value, so listeners cannot change your state?
Exercise
A teammate writes this handler, and the parent's onitemremoved handler logs undefined for event.detail.id. Identify the two problems and show the fixed code.
removeItem() {
const evt = new Event('itemremoved', { detail: { id: this.itemId } });
}
Show answer
First, Event ignores detail, so the payload is dropped. Second, the event is never dispatched, so the parent could not receive it at all. Because the handler is not called, the "undefined" the teammate sees likely comes from a different path, but both bugs must be fixed. The corrected code uses CustomEvent and dispatches it:
removeItem() {
const evt = new CustomEvent('itemremoved', { detail: { id: this.itemId } });
this.dispatchEvent(evt);
}
Exercise
What are the default values of detail, bubbles, composed and cancelable when you call new CustomEvent('ping') with no options? Name one situation where you would change each of the last three.
Show answer
detail is null, and bubbles, composed and cancelable are all false. Set bubbles: true when an ancestor above the direct parent, such as a wrapper element in the parent's template, must receive the event. Set composed: true when the event must cross a shadow boundary to reach a listener outside the parent's template. Set cancelable: true when the child checks the return value of dispatchEvent and skips an action if a listener called preventDefault().