Communicate with Events in LWC Simplified | Child to Parent | Salesforce

Communicate with Events in LWC Simplified

Custom Events in LWC

Hey Kid! you know there is something common between you and me that we both believe in constant learning that too in this tough time so Congratulations πŸŽ‰to you for that. 

In the last EPISODEwe discussed how we can pass the value from parent component to child component by using @API public decorator along with some cool component.

In this EPISODE, we will discuss the reverse order of passing the value i.e. from Child to Parent component by using custom events. Relax!! this is not something which can interrupt you to develop any component.

Do you remember the struggle we have to do while using the custom events in Lightning Aura components in Salesforce? (Please do not laugh) I know we have to create the separate event define the type of the event then we need to register the event and finally, we need to handle the event in the component where we required this value.
But this time because of LWC's modern framework there is no more struggle for that, Yess!! you heard that correctly. In LWC we just have to use CustomEvent() constructor in child component and then handle it in the parent component.

Let's understand the concept we will use to achieve this and then we will move ahead towards our live demo with the simple example.

Understand The Concept of CustomEvents in LWC :
Communicate with Events in LWC Simplified

If you take a look at the above picture, you can see we have Parent component in Pink color and Child component in purple color below that.
Now, let's take a more closer look and now we can see the 3 steps in the picture which we need to follow in order to use the CustomEvents in LWC component.

And the purple Arrow is Event Dispatcher which is responsible for carrying data from child to parent.

These steps are starts from child to parent like this :

STEP 1 : 
Create a custom event inside the event handler method in javaScript file of your Child Component (which is handling value you want to pass to parent). 

Then create const(constant) variable storeEvent in our case to store the CustomEvent instance where we will define EVENT NAME ("myevent" in the above case) and VALUE TO PASS ("this.testValue" in the above case) in front of detail like {detail: 'Your Value'}. 

NOTE : Please note that the value you are passing should be String, integer or Boolean format as you cannot pass the complete object data with the detail as Objects are immutable. 

And finally, we will use this.dispatchEvent(storeEvent) to dispatch the event and now it is ready to take off.

STEP 2 :
As the event is dispatched from the child component we need to handle it right? For that go to your HTML(Markup file) of the parent component. 

Look for <c-child></c-child> (Child Component) defined and then add on+CustomEventName (In our case CustomEvent Name is "myevent" Hence we have used onmyevent )

for example :
<c-child onmyevent={handleResponse}></c-child>

Just like the above code, we mentioned on + myevent (onmyevent) and handleResponse will be out javaScript method which will help us to unwrap the gift(value) which his child sent.

TIP : Hence please do not use on+xyz for defining your normal parameters in MarkUp and it is not recommended too (I know you're smart and you will take care of this).

STEP 3 :
As you might already know by this time its time to unwrap the gift sent by child component inside out javaScript file of LWC Parent component.

Just goto your parent component's .JS file and handle it carefully.

In our case, we have defined handleResponse as our javaScript method that will handle the event whenever its dispatched from the child.

Let's consider the below snippet from the picture :

   this.response = event.detail;
//For additional information console the event 
    console.log('Event =>>'+JSON.stringify(event));

Just like the above code inside handleResponse we handle the event (as a parameter). Where we just need to set the event.detail value to any variable.

As you can see I have used the console.log so that we can actually see what all parameters this event contains. we will take a closer look in the live component demo just after understanding this.

And now in the above code, the value sent from the child component is stored in this.response variable and now that can be used wherever you wish to as the gift is unwrapped now you can play with it Kid.

Alright!! Now you have a basic understanding of the flow of customEvents in LWC. There are different type of event Phases as well like bubble and capture which we will discuss in the upcoming Episodes.

Now let's create a basic demo component for this, Excited??

Let's get started.......

STEP 1 :
Let's create the first Child Component called customEventChild Lightning web component in your VS Code (Ctrl+Shift+P -> Create New Lightning Web Component)
For VS code setup and org authorisation please visit the very first blog of LWC series.

Now create the files as follows : 

<span style="margin-left:1em;">
<lightning-button label="child"

In the above, code we created a simple lightning button inside the child component where the label is child, button variant is brand and finally onclick of the button we will call handleClick method written in a javaScript file.

Now let's look at JavaScript file of the same component

STEP 2 :

import { LightningElement ,track} from 'lwc';
export default class CustomEventChild extends LightningElement{
@track test = 'Value received from child';
const storeEvent = new CustomEvent('myevent',
{ detail: this.test}

In the above file, we have test variable with 'Value received from child' string as a default.
Then we have out onclick method called handleClick method where we are passing (event) as a parameter.

Then we defined storeEvent constant variable to store the event and we created and a new instance of CustomEvent with event parameter 'myevent' and we are passing the this.test (which contains the string 'Value received from child').

At last, we use used this.dispatchEvent(storeEvent) to dispatch the event.
And now its time to handle this event in our parent component right Kid?

STEP 3 :

Let's create a parent component called customEventParent Lightning Web Component (Ctrl+Shift+P -> Create New Lightning Web Component).

<h1 style='font-size:1.5em; margin-left:45%;'
This is parent screen
<span style="font-size:2em;margin-left:30%;">
This is response from child :
<span style="color:#ffa372;">
//Child component included here
<c-custom-event-child onmyevent={handleResponse}>

In the above Parent Component .html file, we have a lightning card on which we have the heading text and included child component and as you can see Kid we also have onmyevent to handle the any dispatched value from child component inside handleResponse javaScript method.

Now let's check the .js file of the same Parent Component.

import { LightningElement ,track} from 'lwc';
export default class CustomEventParent extends LightningElement{
@track response = '';
//here we handled the event
this.response = event.detail;
console.log('Event =>>'+JSON.stringify(event));

In the above .js file, we can see we have defined response variable with @track property to track any change and reflect on the UI which is by default ' ' Empty.

And lastly we handled the event in handleResponse method where every time when user will click on child component button the response will be captured by child component here.

As the response from child component is inside detail of event hence we used event.detail and stored it in this.response variable.

Now if you use this {response} variable on html markup file on the parent component it will immediately update the value with the latest value received from the child component as we used @track property for the same purpose.

Also, I have included console.log to see what all parameters this event contains and will see in the output preview.

For a preview of your output either you can use Preview Component on Local Development server (check out first LWC episode for the same)or you can deploy it to your org by just deploying your component and add it to any aura application and preview it or 

go to parent component .meta.xml file and copy-paste the below snippet and put it to any record or lightning page : 

<?xml version="1.0" encoding="UTF-8"?>

Once deploy it or preview component locally it will look like this :
Communicate with Events in LWC Simplified

Now as you can see we have created parent and child section. Now Click on Child button and you will receive the value inside your parent component like this :

Communicate with Events in LWC Simplified

Whoooooo!! can you see "Value received from a child" value received from child with the help of LWC customEvent

Now you are ready to use this in your LWC component development where there is nested parent-child component and you need to pass the value you can use the same technique for that.

Also, we used console.log to see what all parameters are there along with the detail of the event so here is the console log of the same :

Communicate with Events in LWC Simplified

Now in the console as you can see there are other parameters are involved in the single event object. These are the parameters which also gets captured when you dispatched the event.

In this way, we can use CustomEvent in Salesforce Lightning Web Component easily. If you strongly believe in these steps and ways to use it you are ready to apply this while designing your component...So let's create something valuable LWC Component with this concept Kid πŸ˜‰.

If you like this SFDCkid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you all ⚡️Happy Learning ☁️⚡️ (Learn. Help. Share.) 😊 

<< PREVIOUS                       NEXT >>

SFDCKID on Google Play Store |

Communicate with Events in LWC Simplified | Child to Parent | Salesforce  Communicate with Events in LWC Simplified | Child to Parent | Salesforce Reviewed by on Rating: 5


  1. i am facing error UNKNOWN EXCEPTION while deploying it to org

  2. Please check "" as if you copy and paste the code it some times throw error.

  3. The slam was awesome. We made happy and amused ourselves through the evening. web-based reserved seating software

  4. Why isn't you old material available? Anything before basic series episode 4 doesn't open. Could be nice to have access. I would like to learn

    1. Hello Javeria, I just checked and found that links are opening perfectly fine. If you are still facing issue please share the non working lonks so that we can fix them.

      Happy Learning!!



Powered by Blogger.