Send an object via Events in LWC

In this blog, we will be looking at how to send objects via events in LWC.

In the last blog post we looked at how to fire events and send data.

In this blog we will be looking at how to send complex data types (objects) via events.

Here is the snippet which demos that!

import { LightningElement } from "lwc";

export default class ExploreEventsBubbling extends LightningElement {

    handleClick() {
        const detail = {
            name: 'Teja',
            age: 100,
            location: 'World',
            address: {
                city: 'I dont know',
                state: 'I will not say',
                country: 'No mans land'
            }
        }
    
    this.template.querySelector("p").dispatchEvent(
      new CustomEvent("teja", {
        detail: person
      }));
      
      /* This also is valid code
       * this.template.querySelector("p").dispatchEvent(
       *   new CustomEvent("teja", {
       *     detail
       *   });
       * );
       */
    
  }
}
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

Also, in an object when key and value are having the same naming convention, we can just use this notation.

new CustomEvent("teja", {
    detail //this line is similar to details : details
});
This is also valid JavaScript
<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 name we use the 
      //notation which is event.detail.name
      console.log(event.detail.name);
      console.log(event.detail.age);
      console.log(event.detail.address.state);
      console.log(event.detail.address.city);
  }
}
ParentEventBubbling.js

Hope this helps!