Events in LWC

Everything that you should know about events in LWC.

Events in LWC

By now we know that events are used to send data across the DOM tree. There is also an absolute need for us to understand how can we incorporate Events in LWC.

This post, Events in LWC is an extension to the previous post Event in JS, do check it out, it helps you get a better understanding of how events work in the first place.

How to dispatch an Events in LWC

Dispatching an event in LWC is a 2 step process.

We need to have an element or button on click on which we need to fire or dispatch the event.

It's not that we can only dispatch the event on click of an element. We can also dispatch the event on double of an element, on hover of an element and etc.

Dispatching the event using the notation this.dispatchEvent(new CustomEvent("send"))

Here dispatchEvent is used to dispatch the event and we also need to provide an event name that we wish to dispatch.

In the above syntax am trying to dispatch a custom event and the name of the event is send.

Here is a sample complete method that's trying to dispatch an event in LWC

handleClick()
{
	this.dispatchEvent(new CustomEvent("send"));
}	

In case I want to add the event listener to this event then I need to use the notation onsend on one of the parent elements of the element where we will be eventually clicking.

<div onsend={handleSendData}>
	<lightning-button label="Send Data" onclick={handleClick}></lightning-button>
</div>

Here is the complete example ...

This is the template file

<!--EventCommunication.html -->
<template>
  <lightning-button label="send data" onclick={handleSend}></lightning-button>
</template>

and this is the JS file

//EventCommunication.js
import { LightningElement } from "lwc";

export default class EventCommunication extends LightningElement {
  handleSend() {
    this.dispatchEvent(new CustomEvent("senddata"));
  }
}

Very rarely we will be dispatching the event without any data attached to it and most of the times we will have to send data along with events. And in such scenarios We can send primitive data or custom defined data.

  • Passing primitive data types via events
  • Passing custom defined data types via events

Here are all the variants that are possible with events in LWC