SFDC Stop - Always the latest about Salesforce


Full Tutorial Series with videos, free apps, live sessions, salesforce consulting and much more.


Telegram logo   Join our Telegram Channel

Friday 24 February 2023

Child to Parent communication using LWC Events | LWC Tutorial | Lightning Events in LWC

Hello Trailblazers, 

I recently posted the below video on SFDC Stop YouTube Channel where we learned how can we communicate from a child lwc to a parent lwc using events.

Tutorial Video

In this post, I'm going to share the code snippet we used in the above tutorial with a brief explanation of the same. You can watch the small ~9min video, I shared above to learn the concept in detail.

Let's have a look at the code snippets now!

Child LWC

First of all, we created a child lwc. This component will fire the event on a button click, which will be handled by the parent lwc. Let's have a look at the HTML and Js code of our child lwc one by one:

child.html

<template>
    <lightning-button label="Increase Count" onclick={increaseCount}></lightning-button>
</template>
As you can see above, we defined a lightning button with label Increase Count, this button will call the js method increaseCount() which will increase the value of a counter we'll define in our js and fire an event. The parent LWC will capture the event and will display the value of this counter along with some text received in the event body.

child.js

import { LightningElement } from 'lwc';

export default class Child extends LightningElement {

    count = 0;

    increaseCount() {
        this.dispatchEvent(new CustomEvent('increasecount', {
            detail: {
                message: 'Increased count to ' + (++this.count)
            }
        }));
    }
}
As you can see above, we defined a variable count whose initial value is 0. As we click the Increase Count button, this increaseCount() will be called. It'll dispatch a new event named increasecount and in the body of this event (which is an object), we defined a property named detail. Now, in this detail property, we can pass anything, it can be a string, an array, an integer, an object...anything.

For now, in the detail of this event, we're passing an object, which has a single property named message and the value of message is: Increased count to <increased value of count variable>. This means, each time this method is called, count variable will be incremented by 1 and the string message will be passed in event detail which has the updated count. For example, when the first time, this method is called, we will have the message Increased count to 1 in the event detail. Similarly, the second time this method is called when the button is clicked again, count variable will increase again by 1 and the message: Increased count to 2 will be passed in the event detail.

Our parent lwc will accept this event and will display the message. Let's have a look at that now!

Parent LWC

Let's start by looking at the html part again:

parent.html

<template>
    <lightning-card title={message}>
        <p class="slds-var-p-around_small">
            <c-child onincreasecount={updateMessage}></c-child>
        </p>
    </lightning-card>
</template>
In this component, first of all we defined a lightning-card with title equal to the message variable that we'll define in our js. Then, for the card body, we defined a paragraph with a small padding and within that paragraph, we called our child component. Now, we know that our child lwc will fire increasecount event when the button is clicked, so we're handling the same event as: onincreasecount={updateMessage}. This means: whenever this increasecount event is fired, it'll call the updateMessage() method defined in the js of our parent lwc.

For every event which is fired by a child lwc, you can handle it by adding a prefix on before it's name and then binding it to a method defined in your js. For example: here our event name is increasecount so we added the on prefix before event name and it became: onincreasecount and we binded it to our updateMessage() method defined in our js. This updateMessage() method will receive the same event that we fired from our child component. Let's checkout the js to understand how we're handling this event.

parent.js

import { LightningElement } from 'lwc';

export default class Parent extends LightningElement {

    message = 'Updated count will appear here!';

    updateMessage(event) {
        this.message = event.detail.message;
    }
}
As you can see in the above code snippet, we defined a message variable in our js. This is the same variable which is used as the value of title in our lightning card. The default value of this variable is Updated count will appear here! so by default the lightning card will display this message as you can see in the below screenshot:


We also defined a method updateMessage(event), this method will receive the same event which is fired by our child lwc in the parameter and will update the message variable with the value that is coming from the message property of our event detail object. Remember, we defined an object in the detail property of our event body, with a single property named: message whose value was Increased count to <increased value of count variable>? So, when we do: this.message = event.detail.message; we're basically saying, get the object defined in detail property of event body (event.detail) and then get the value of message property from that object (event.detail.message). We're assigning the value of this message property from event detail object to our message variable and this message variable is displayed as the title of our lightning card.

parent.js-meta.xml

I'm going to add this component to my homepage for the demo, so I've added a target named lightning__HomePage as shown below:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>56.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Demo

Now, as we click on the Increase Count button once, the child component's counter (count variable) will increment to 1, the value of message will be Increased count to 1, the lightning card title will update and the output for the same is shown below:


Similarly, as we click on this button again, the child component's count variable will update to 2, the message passed through the event will be Increased count to 2 and the same message will be displayed in the title of our lightning card as shown below:


I'm sharing a small screen recording below so that it's clear how the component is behaving in real time:


That's all for this tutorial everyone, I hope you liked it. Let me know your feedback in the comments down below.

Happy Trailblazing!!

No comments:

Post a Comment