Sunday, March 26, 2023

Custom Events in Lightning Web Components : Pass data from child component to parent component

In order to communicate from child component to parent component in LWC, we use custom events. Custom events helps in passing data from child components to parent component in containment hierarchy.

If you want to refer on how same thing can be achieved in Aura Components then refer below article:

Component Events: Way to Communicate Between Components in Containment Hierarchy


Lightning component can create and dispatch events in a component’s JavaScript class. To create an event, use the CustomEvent() constructor. To dispatch an event, call the EventTarget.dispatchEvent() method.

The CustomEvent() constructor needs one required parameter, which is a string indicating what event has been performed. You can define ant string as event name. While defining event name, follw below recommendation based on DOM event standard.

  • No uppercase letters
  • No spaces
  • Use underscores to separate words

Steps involved in implementing custom events

1. Create custom event in child component and dispatch that event.

    const newEvent = new CustomEvent("search");
    this.dispatchEvent(newEvent);

2. Handle the event in parent component.

When you declare the child component in parent component, then use "on" event handler to execute logic whenever the event is fired. Suppose you event name which is dispateched from child component is "search", event handler name will be "onsearch".

<c-sk-child-cmp onsearch={capturedEvent}></c-sk-child-cmp>
capturedEvent(event) {
    console.log("**recieved event-->" + event);
}

Custom events to inform what action is performed in child component

If you want to inform parent component about what has been clicked or operation performed in child component, then you can simply define custom event as mentioned below:

<template>
    <lightning-button label="Edit" onclick={editAction}></lightning-button>
    <lightning-button label="New" onclick={deleteAction}></lightning-button>
</template>

    editAction() {
const newEvent = new CustomEvent("edit");
        this.dispatchEvent(newEvent);
    }

    deleteAction() {
const newEvent = new CustomEvent("delete");
        this.dispatchEvent(newEvent);
    }


Custom events to pass data to parent component

If you want to pass data to parent component, then set a detail property in the CustomEvent constructor. 

You can pass any record id  or any data from child component in detail property.

@track selectedRecordId;

handleResponse(event) {
const answerEvent = new CustomEvent("search", { detail: this.selectedRecordId});
this.dispatchEvent(answerEvent);
}

Parent component can access detail property in order to read data passed from child component

 capturedEvent(event) {
    console.log("**recieved event detail-->" + event.detail);
 }


Note: There is no restriction on data type of detail property but is is recommended to pass only primitive data. JavaScript passes all data types by reference except for primitives. If a component includes an object in its detail property, any listener can mutate that object without the component’s knowledge. This is a bad thing! It’s a best practice either to send only primitives, or to copy data to a new object before adding it to the detail property. Copying the data to a new object ensures that you’re sending only the data you want, and that the receiver can’t mutate your data.

Lets try to understand custom events through simple example:

We will create a child component "skChildCmp" which will contain few buttons. Once user will click on one of the button, child component will pass resource URL based on button click to parent component and parent component will display that URL.

Below is snapshot for parent component:


Now when user clicks on SFDCSTUFF BLOGS button, URL for that button will be appearing on parent component.


If user clicks on TRAILHEAD button, then parent will display URL for that.


Below is complete code snippet:



Hope this will help!!