Child To Parent Communication in LWC

Telegram logo Join our Telegram Channel

How to send data to parents from the child LWC component?

To send data from the child component to the parent component we need to use the custom event from JavaScript. JS custom events are custom DOM events that we can use to communicate between the components.

Creating and dispatching/triggering the event

We can create the custom event by providing the name and optionally event data by using the CustomEvent object below. You can use your desired name for the event.

const event = new CustomEvent("myevent", { detail: elem.dataset.time });

We can trigger the event by using the dispatchEvent, like below.

elem.dispatchEvent(event);

Rules for naming the custom event.

As we can name the custom event as per our requirement there are some things to be considered while naming the custom event.
  1. The event name is always all-lowercase characters without any dash or underscore.
  2. Do not start a property name with ‘on’, ‘aria’, or ‘data’. Also do not use reserved keywords like ‘slot’, ‘part’, or ‘is’ - doing so can create confusion or unidentifiable errors.
  3. Do not start the name of the custom event with ‘on’. Because when the event is handled from the parent component it needs to be prefixed with ‘on’. So adding ‘on’ at the beginning will create confusion.
  4. You can underscore in the event name but I would recommend not to use that as it does not follow HTML.

Handling the event from the parent component

In the parent component, we handle the event by attaching the event handler function, adding the handler function as an attribute to the child component tag like below. 

Prefix the custom event name with on and attach the handler like below. For example, if your event name is myevent then the attribute name will be onmyevent.

<template>
     <c-child-component onmyevent={handleIncrementFromChild}></c-child-component>
</template>


Create a child component to fire an event.

Create a child component to send that to the parent component at the click of a button, using the custom events in JavaScript.

HTML

<template>
    <lightning-card variant="compact">
        <div slot="title">
            Child Component
        </div>

        <div>
            <lightning-button
                variant="brand"
                label={buttonLabel}
                onclick={incrementCounter}
            ></lightning-button>
        </div>
    </lightning-card>
</template>

JS

import { LightningElement } from "lwc";

export default class ChildComponent extends LightningElement {
    counter = 0;

    incrementCounter() {
        this.counter++;
        // send data to parent using the custom event
        const increment = new CustomEvent("increment", {
            detail: { counter: this.counter }
        });
        this.dispatchEvent(increment);
    }

    get buttonLabel() {
        return `Count (${this.counter})`;
    }
}


Handle the event in the parent component

The parent component is adding the handler to receive the data sent from the child component.

HTML

<template>
    <lightning-card variant="compact">
        <div slot="title">
            Parent Component, counter value : {counter}
        </div>

        <div>
            <c-child-component onincrement={handleIncrementFromChild}></c-child-component>
        </div>
    </lightning-card>
</template>

JS

import { LightningElement } from "lwc";

export default class ParentComponent extends LightningElement {
    counter = 0;

    handleIncrementFromChild(event) {
        console.log("message received from child component");
        this.counter = event.detail.counter;
    }
}

Related Articles


No comments :
Post a Comment

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com