Pass Data in an Event

By in
357
Pass Data in an Event

Set a detail property in the CustomEvent function Object() { [native code] } to send data to a receiving component. The event listener’s handler function provides access to the data in the detail property for receiving components.

The detail property is not subject to any type restrictions or structure thanks to the CustomEvent interface. However, it’s crucial to send simply basic information. All data types other than primitives are sent by reference in JavaScript. Any listener can modify an object that a component contains in its detail property without the component’s awareness. This is not good! Either sending only primitives or copying data to a new object before adding it to the detail property are excellent practices. You can communicate only the data you want by copying it to a new object, which prevents the recipient from changing your data.

Let’s examine the lwc-recipes repository’s c-event-with-data component.

A nested c-contact-list-item component makes up each entry in the list of contacts.

The contact name and image are enclosed in an anchor tag by the c-contact-list-item component, and the selectHandler function is called by a onclick event listener.

 

<!– contactgWListItem.html –>

<template>

<a href=”#” onclick={selectHandler}>

<lightning-layout vertical-align=”center”>

<lightning-layout-item>

<img src={contact.Picture__c}></img>

</lightning-layout-item>

<lightning-layout-item padding=”around-small”>

<p>{contact.Name}</p>

</lightning-layout-item>

</lightning-layout>

</a>

</template>

 

// contactWgListItem.js

import { LightningElement, api } from ‘lwc’;

 

export default class ContactWgListItem extends LightningElement {

@api contact;

 

selectHandler(event) {

// Prevents the anchor element from navigating to a URL.

event.preventDefault();

 

// Creates the event with the contact ID data.

const selectedEvent = new CustomEvent(‘selected’, { detail: this.contact.Id });

 

// Dispatches the event.

this.dispatchEvent(selectedEvent);

}

}

 

Event and Function
Image Source: Developers.Salesforce

The component assigns the contactId property to the event.detail property in the handler for the contactSelected event. The contact’s name, title, phone number, and email are displayed in the template after the contact with that ID is located in the contacts array provisioned by @wire.

 

Conclusion

In this way, we can use detail property of the CustomEvent() object to create custom javascript event with data in it and to send out the events we use dispatch method.

 

To learn more about Lightning Web Components, check out some of my related blogs below!

 

Additional Resources

Cover Photo by RoseBox رز باکس on Unsplash

Leave a reply

Your email address will not be published. Required fields are marked *