Send data via Events in LWC

Let's look at how to send data via events in LWC.

When we work with events it's absolutely necessary that we send data along with the event, I mean, if it's not for sending the data why would we even need events in the first place?

So by now, we have a hang of how to fire the events, so now, let's look at how to send the data in events.

The syntax is not going to change a lot just because we need to send data, there will be a config object that we need to tinker around to send the data to the parent or containing component.

Here is a snippet of the code demonstrating it!

import { LightningElement } from "lwc";

export default class ExploreEventsBubbling extends LightningElement {

    message = 'HEY!!! Salesforce Casts';

    handleClick() {
    this.template.querySelector("p").dispatchEvent(
      new CustomEvent("teja", {
        detail: this.message
      })
    );
  }
}
exploreEventsBubbling.js

Here is the template file, it's pretty much straightforward. This is just going to fire the event because of the user input and from there the JavaScript is going to take care of the rest of it.

Just a heads up it's not details its just detail

<template>
  <div>
    <span onteja={handleCustomEvent}>
      <p onteja={handleCustomEvent}>
        <lightning-button
          label="Click Me"
          onclick={handleClick}
        ></lightning-button>
      </p>
    </span>
  </div>
</template>

exploreEventsBubbling.html

This is the parent or containing component.

<template>
    <p onteja={handleParentEvent}>
        <c-explore-events-bubbling></c-explore-events-bubbling>
  </p>
</template
parentEventBubbling.html

Here is the controller file in the parent component.

import { LightningElement } from "lwc";

export default class ParentEventBubbling extends LightningElement {
  handleParentEvent(event) {
      //because the property name is message we use the 
      //notation which is event.detail.message
      console.log(event.detail.message);
  }
}
parentEventBubbling.js

Hope this helps!