Mastering Custom Events in Salesforce LWC with Real-Time Examples

Custom Events in Salesforce LWC with Real-Time Examples
Chinmaya By Chinmaya
7 Min Read

Introduction

In Salesforce Lightning Web Components (LWC), communication between components is very important, especially in complex applications with multiple components are interacting with each other dynamically.

Custom events in LWC enable components to communicate effectively by allowing Child LWC components to pass information or actions to Parent LWC components.

In this blog post, we will understand – Custom Events in detail, explaining their creation, usage, and a practical example.

Understanding Custom Events in LWC

Custom events are used to send data and make communication from Child LWC component to Parent LWC component.

This communication from Child component to Parent component is implemented using the CustomEvent constructor and dispatched using the dispatchEvent() method.

Key Concept

To set up communication from Child LWC component to Parent LWC Component, a Salesforce developer must implement the below 3 steps.

1. Creating a Custom Event

A custom event is created using the CustomEvent constructor, which takes two arguments:

    • Event Name: The name of the event (string). It must follow the kebab-case naming convention.
    • Event Details: An object containing the data you want to pass to the parent component.
				
					const myEvent = new CustomEvent('eventname', {
    detail: { key: 'value' }
});
				
			

2. Dispatching a Custom Event

The custom event is dispatched using the dispatchEvent() method. This sends the event to the parent component.

				
					this.dispatchEvent(myEvent);
				
			

‘myEvent’ is the custom event name which you have created in Step 1.

3. Listening to Custom Events

There are two ways to listen to a Custom event from Child Component:

    • Declarative way :
      We need to add “on” prefix in the event name in Parent Component’s .HTML file.
				
					<template>
<c-child-component oneventname={handleEvent}></c-child-component>
</template>
				
			
    • JavaScript using addEventListener method :
      We can explicitly attach a listener by using the addEventListener method in the parent component’s Javascript file like below : 
				
					this.template.addEventListener('eventName', this.handleNotification.bind(this));
				
			

Example 1: Creating and Dispatching Custom Events and Listening in Declarative way

Scenario

We’ll build a simple LWC application where a child component sends a message to the parent component using a custom event.

Step 1: Create the Child Component

Create a child component named childComponent.

childComponent.html

				
					<template>
    <lightning-button label="Send Message" onclick={sendMessage}></lightning-button>
</template>
				
			

childComponent.js

				
					import { LightningElement } from 'lwc';

export default class ChildComponent extends LightningElement {
    sendMessage() {
        const eventDetail = { message: 'Hello from Child Component!' };
        const messageEvent = new CustomEvent('message', { detail: eventDetail });
        this.dispatchEvent(messageEvent);
    }
}
				
			

Step 2: Create the Parent Component

Create a parent component named parentComponent.

parentComponent.html

				
					<template>
    <c-child-component onmessage={handleMessage}></c-child-component>
    <p>{receivedMessage}</p>
</template>
				
			

parentComponent.js

				
					import { LightningElement } from 'lwc';

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

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

Let's check the above code and understand how the communication from child to parent component works

    1. The child component contains a button (having Label = Send Message) that, when clicked, dispatches a message event with a message in the detail property.
    2. The parent component listens for the message event and updates the receivedMessage property with the data from the event.
    3. The updated receivedMessage property is rendered dynamically in the parent component’s template.

Example 2: Creating and Dispatching Custom Events and Listening it using addEventListener method

A parent component listens to a custom event from its child component.
Instead of using template syntax, the parent uses the addEventListener method to handle the event.

Step 1: Create the Child Component

Create a child component named childComponent.

childComponent.html

				
					<template>
    <lightning-button label="Click Me" onclick={fireCustomEvent}></lightning-button>
</template>
				
			

childComponent.js

				
					import { LightningElement } from 'lwc';

export default class ChildComponent extends LightningElement {
    fireCustomEvent() {
        const customEvent = new CustomEvent('message', {
            detail: { message: 'Hello from Child Component!' }
        });
        this.dispatchEvent(customEvent);
    }
}
				
			

Step 2: Create the Parent Component

Create a parent component named parentComponent.

parentComponent.html

				
					<template>
    <div>
        <p>Message from Child: {receivedMessage}</p>
        <c-child-component></c-child-component>
    </div>
</template>
				
			

parentComponent.js

				
					import { LightningElement } from 'lwc';

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

    connectedCallback() {
        // Add an event listener dynamically
        const childElement = this.template.querySelector('c-child-component');

        // Use a timeout to wait until child component is rendered
        setTimeout(() => {
            if (childElement) {
                childElement.addEventListener('message', this.handleMessage.bind(this));
            }
        }, 0);
    }

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

How It Works?

  1. Child Component:
      • Dispatches a custom event named message with a detail object containing a message.
  2. Parent Component:
      • Uses the connectedCallback lifecycle hook to dynamically attach an event listener to the child component using addEventListener.
      • The handleMessage method is invoked when the custom event is triggered, and it updates the receivedMessage property.
  3. Rendering Order:
      • The setTimeout ensures the child component is fully rendered before attaching the event listener. Without it, querySelector might not find the child element immediately.

Best Practices for Using Custom Events

1. Use Clear and Descriptive Names:

Always use descriptive names for custom events to ensure clarity in code.

2. Avoid Overusing Events:

While custom events are powerful, overusing them can make debugging difficult. Use them only when necessary

3. Use composed: true (if needed):

If the event needs to propagate beyond the parent component, set the composed option to true.

				
					const myEvent = new CustomEvent('eventname', {
    detail: { key: 'value' },
    bubbles: true,
    composed: true
});
				
			

4. Avoid Redundant Listeners:

Ensure listeners are added only when necessary to prevent duplicate handling of events.

5. Use Template Syntax When Possible:

For straightforward event handling, prefer the template syntax (on<eventname>).
Use addEventListener for more complex scenarios.

6. Memory Management::

Always clean up event listeners (e.g., in the disconnectedCallback hook) to avoid memory leaks.

Conclusion

Custom events in LWC provide an efficient way to facilitate communication between child and parent components.
By understanding and implementing custom events, you can build robust, maintainable applications that effectively manage data flow.

 For more insights into LWC and other Salesforce topics, explore more articles on Writtee!

Happy Coding! 😊

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
Leave a comment