Child to Parent Communication using LWC Events

  • Post author:
  • Post category:LWC

LWC Tutorial | Lightning Events in LWC

In Lightning Web Components, child-to-parent communication is handled using custom events. This is a core concept in LWC where a child component fires an event, and the parent component listens to it.


📘 Use Case

Imagine a child component has a button that, when clicked, sends data back to the parent component. This could be a selected record, input value, or action signal.


🧩 Step-by-Step Example

🔹 1. Child Component (childComponent.js)

HTML (childComponent.html):

<template>
    <lightning-button label="Send to Parent" onclick={handleClick}></lightning-button>
</template>
import { LightningElement } from 'lwc';

export default class ChildComponent extends LightningElement {
    handleClick() {
        const customEvent = new CustomEvent('message', {
            detail: { message: 'Hello from Child!' }
        });
        this.dispatchEvent(customEvent);
    }
}
  • message is the event name.
  • detail is the payload sent to the parent.

🔹 2. Parent Component (parentComponent.js)

HTML (parentComponent.html):

<template>
    <c-child-component onmessage={handleMessage}></c-child-component>
    <p>{receivedMessage}</p>
</template>
import { LightningElement } from 'lwc';

export default class ParentComponent extends LightningElement {
    receivedMessage = '';

    handleMessage(event) {
        this.receivedMessage = event.detail.message;
    }
}

onmessage={handleMessage} listens to the custom event from the child.

The value from the event (event.detail.message) is handled and shown.