Vinod Sebastian – B.Tech, M.Com, PGCBM, PGCPM, PGDBIO

Hi I'm a Web Architect by Profession and an Artist by nature. I love empowering People, aligning to Processes and delivering Projects.

Advertisements




Salesforce Lightning Web Components Communication

Parent-Child Component Communication

In Salesforce Lightning Web Components (LWC), communication between parent and child components is essential for building interactive and dynamic user interfaces. This communication can be achieved using public properties marked with @api to pass data from parent to child components.

Child Component (receives data via @api)

Let’s start with the child component, which receives data from the parent component through a public property.

childComponent.js

import { LightningElement, api } from 'lwc';

export default class ChildComponent extends LightningElement {
  @api message; // public property, reactive
}

childComponent.html

<template>
  <lightning-card title="Child Component">
    <p class="slds-p-around_medium">
      Message from Parent: {message}
    </p>
  </lightning-card>
</template>

Parent Component (passes data to child)

Now, let’s look at the parent component, which passes data to the child component using the public property defined in the child component.

parentComponent.js

import { LightningElement } from 'lwc';

export default class ParentComponent extends LightningElement {
  parentMessage = 'Hello from Parent!';
}

parentComponent.html

<template>
  <lightning-card title="Parent Component">
    <p class="slds-p-around_medium">
      Parent says: {parentMessage}
    </p>

    <!-- Pass data to child via @api property -->
    <c-child-component message={parentMessage}></c-child-component>
  </lightning-card>
</template>

Child-Parent Component Communication

In Salesforce Lightning Web Components, child components can communicate with their parent components by dispatching custom events. This mechanism allows child components to notify parent components of changes or trigger specific actions in the parent component.

Let’s explore how child components can dispatch custom events to communicate with their parent components.

Child Component (dispatches event)

childComponent.js

import { LightningElement } from 'lwc';

export default class ChildComponent extends LightningElement {
  handleClick() {
    // Create and dispatch a custom event
    const myEvent = new CustomEvent('sendmessage', {
      detail: { text: 'Hello Parent, from Child!' }
    });
    this.dispatchEvent(myEvent);
  }
}

childComponent.html

<template>
  <lightning-card title="Child Component">
    <lightning-button label="Send Message to Parent" onclick={handleClick}></lightning-button>
  </lightning-card>
</template>

Parent Component (listens for event)

In the parent component, we need to listen for the custom event dispatched by the child component to receive and handle the data sent by the child.

parentComponent.js

import { LightningElement } from 'lwc';

export default class ParentComponent extends LightningElement {
  parentMessage;

  handleMessage(event) {
    this.parentMessage = event.detail.text;
  }
}

parentComponent.html

<template>
  <lightning-card title="Parent Component">
    <p class="slds-p-around_medium">
      Message received from Child: {parentMessage}
    </p>

    <!-- Listen for custom event from child -->
    <c-child-component onsendmessage={handleMessage}></c-child-component>
  </lightning-card>
</template>

Publish-Subscribe Pattern

The publish-subscribe pattern, also known as Pub/Sub pattern, is a messaging pattern commonly used for communication between multiple components in an application. In Salesforce Lightning Web Components, the Pub/Sub pattern can be implemented using a central event bus or a third-party library to facilitate communication between components that are not directly related.

Let’s dive into how we can implement the Pub/Sub pattern in Salesforce Lightning Web Components.

Create a PubSub Utility

First, we need to create a utility for the Pub/Sub pattern that allows components to subscribe to and publish events.

pubsub.js

const events = {};

const subscribe = (eventName, callback) => {
  if (!events[eventName]) {
    events[eventName] = [];
  }
  events[eventName].push(callback);
};

const unsubscribe = (eventName, callback) => {
  if (events[eventName]) {
    events[eventName] = events[eventName].filter(listener => listener !== callback);
  }
};

const publish = (eventName, payload) => {
  if (events[eventName]) {
    events[eventName].forEach(callback => {
      try {
        callback(payload);
      } catch (error) {
        console.error(error);
      }
    });
  }
};

export default {
  subscribe,
  unsubscribe,
  publish
};

Publisher Component (publishes event)

Next, we have a publisher component that publishes an event using the Pub/Sub utility created earlier.

publisherComponent.js

import { LightningElement } from 'lwc';
import pubsub from 'c/pubsub';

export default class PublisherComponent extends LightningElement {
  handleClick() {
    pubsub.publish('messageEvent', { text: 'Hello from Publisher!' });
  }
}

publisherComponent.html

<template>
  <lightning-card title="Publisher">
    <lightning-button label="Publish Message" onclick={handleClick}></lightning-button>
  </lightning-card>
</template>

Subscriber Component (consumes event)

Lastly, we have a subscriber component that subscribes to the event published by the publisher component and consumes the data sent through the event.

subscriberComponent.js

import { LightningElement } from 'lwc';
import pubsub from 'c/pubsub';

export default class SubscriberComponent extends LightningElement {
  message;

  connectedCallback() {
    pubsub.subscribe('messageEvent', this.handleMessage.bind(this));
  }

  handleMessage(payload) {
    this.message = payload.text;
  }
}

subscriberComponent.html

<template>
  <lightning-card title="Subscriber">
    <p class="slds-p-around_medium">Received: {message}</p>
  </lightning-card>
</template>