2 Types of Events in Salesforce LWC: A Detailed Guide

2 Types of events in Salesforce LWC
Chinmaya By Chinmaya
5 Min Read

Introduction

Events are essential in Salesforce Lightning Web Components (LWC) for enabling communication between components or handling user interactions like button clicks, field changes, or other actions.

In this blog post, we’ll explore two types of events in Salesforce LWC: Standard Events and Custom Events, with simple examples to help you understand and implement them effectively.

What Are Events in LWC?

Events in LWC allow different components to communicate with each other or respond to user actions.

An event has three key parts:

    1. Event Dispatcher: The component that fires (dispatches) the event.
    2. Event Listener: The component that listens for the event.
    3. Event Data: Optional data passed with the event for further processing.

Types of Events

    1. Standard Events:
      Standard events are pre-defined browser events that facilitate seamless interaction between components and the DOM.
      These events, such as click, change, input, etc., are part of the standard DOM API and are natively supported in LWC.

    2. Custom Events:
      Custom events are user-defined events designed to address specific business requirements, enabling seamless communication between components.

1. Standard Events in LWC

Standard events are predefined browser events that handle user interactions like button clicks, form submissions, or value changes.

For example, when a user clicks a button, the onclick event is triggered.

Example: Handling a Button Click

HTML

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

JavaScript

				
					import { LightningElement } from 'lwc';

export default class StandardEventExample extends LightningElement {
    handleClick() {
        alert('Button clicked!');
    }
}
				
			

Explanation

    1. The onclick attribute binds the handleClick method to the click event of the button.
    2. When the button is clicked, handleClick executes, showing an alert.

Commonly Used Standard Events are

    1. click: Triggered when an element is clicked.
    2. change: Fired when the value of an input element changes.
    3. input: Occurs when the user modifies an <input> field.
    4. submit: Triggered when a form is submitted.

Key Points to Remember

    1. Standard events work natively in LWC and do not require special configuration.
    2. You can add event listeners directly in the template using attributes like onclick, onchange, etc.
    3. Always use meaningful method names to improve code readability and maintainability.

2. Custom Events in LWC

Custom events are those allow child components to send data or signals to parent components. These are created using the CustomEvent constructor.

Example: Sending Data from Child to Parent when button is clicked on Child LWC Component

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 messageEvent = new CustomEvent('message', {
            detail: { message: 'Hello from Child Component!' }
        });
        this.dispatchEvent(messageEvent);
    }
}
				
			

parentComponent.html

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

parentComponent.js

				
					import { LightningElement } from 'lwc';

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

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

Explanation

    1. The child component dispatches a message custom event using dispatchEvent.
    2. The parent component listens to the message event using the onmessage attribute.
    3. The handleMessage method in the parent receives the data (event.detail.message) and updates the UI.

Comparison: Standard Events vs. Custom Events

Aspect Standard Event Custom Event

Content

Predefined events like click.
User-defined events for custom use cases
Usage
Handle user interactions.
Communicate between child and parent.
Example
Button click event.
Passing data from child to parent.

Checkout the post below to explore more about Custom Events in Salesforce LWC, complete with examples.

Best Practices for Events in LWC

    1. Use Descriptive Event Names: For custom events, use meaningful names like message, datachange, etc.
    2. Avoid Overusing Custom Events: Use them only when standard events can’t fulfill your requirements.
    3. Document Events: Clearly document the events emitted by a component, especially in complex applications.

Conclusion

Events are the backbone of component communication in Salesforce LWC.
Understanding the difference between standard and custom events helps you design interactive and dynamic components effectively.

For more beginner-friendly guides on Salesforce, visit Writtee!

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