How do you dispatch and handle custom events in LWC?
Suggested answer
Child dispatches: this.dispatchEvent(new CustomEvent('selectitem', { detail: { itemId: this.id, name: this.name }, bubbles: true, composed: false })); Event name convention: all lowercase, no hyphens. Parent handles: In HTML: <c-child onselectitem={handleSelect}></c-child>. In JS: handleSelect(event) { const { itemId, name } = event.detail; }. bubbles: If true, the event bubbles up through the DOM tree. composed: If true, the event crosses shadow boundaries (needed to propagate out of shadow DOM). For LWC within another LWC, typically bubbles: true, composed: false is sufficient for parent to catch the event. For communication across unrelated components, use Lightning Message Service instead of relying on event bubbling.
Practice content for interview preparation; not an official vendor answer. Verify details against current product documentation.
Community comments (0)
No comments yet.
Sign in or create a free account to add a comment. Comments are moderated before they appear.