Sub topic 2
Naming and Handling Custom Events in LWC
Assume you know basic JavaScript, LWC templates, @api properties, and how to place one LWC inside another. A child component sends a signal upward with an event. The parent receives that signal and reads its payload.
Naming your event
Use a lowercase event name with no spaces. Use a verb or verb phrase that describes what happened, such as productselected, itemremoved, or formsubmitted. Do not add the on prefix to the event name. The parent adds that prefix when it listens in markup.
this.dispatchEvent(
new CustomEvent('productselected', {
detail: { productId: this.productId }
})
);The event type is productselected. The parent listener will therefore be onproductselected.
Sending data with `detail`
The detail property carries data from the child. Prefer a small payload containing the values the parent needs. Use a new object rather than exposing the child’s internal state directly.
// 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 }
})
);
}
}Listening in the parent template
The parent listens on the child element. Add on before the event type and assign the attribute to a handler method.
<!-- productList.html -->
<template>
<c-product-tile
product-id="p1"
name="Desk"
onproductselected={handleProductSelected}>
</c-product-tile>
<p>Selected: {selectedId}</p>
</template>Reading `event.detail` in the handler
The handler receives the event object. Read the child’s payload through event.detail.
// productList.js
import { LightningElement } from 'lwc';
export default class ProductList extends LightningElement {
selectedId;
handleProductSelected(event) {
this.selectedId = event.detail.productId;
}
}Assigning selectedId causes the template to render the new value.
Exercise
What listener attribute handles a child event named cartupdated?
Show answer
Use oncartupdated={handlerName}. The event name itself remains cartupdated.