Communication between independent lightning web component and Aura component - aurapubsub

You can use pubsub library or lightning message service to communicate between components that are not in same DOM hierarchy. These methods can be used to communicate between sibling components in an outer lwc component or between to lwc components that are dropped separately in lightning app builder.

Here we will go through an example of lwcComponentA that displays three car company names using radio button. When a car company is selected in the child component we will fire a carselected event from child component with the name selected by the user. Parent component will listen to this event and display the selected name in parent component. Parent component auraComponentB, will listen to this event and display the selected name in auraComponentB.

Example

1) Create a utility lwc component with name pubsub. Copy paste below code into it's JavaScript file. Please note that this is a utility component provided by Salesforce. But current version available in the link is doing pageRef check and it is not working as expected. So use below version shared by another Salesforce team member instead.


2) Create a utility lwc component with name auraPubSub Copy paste below code into it's JavaScript file.Please note that this is a utility component provided by Salesforce.


3) Create a lwc component with name lwcComponentA


4) Create a aura component with name auraComponentB


5) Create a aura test app lwcToAuraSiblingTest in which lwcToAuraSiblingTest.App can contain both components

6) Now if you open the aura app, it will look like

child to parent lwc communication

Explanation

In lwcComponentA component, when value of car is changed in the radio button, it calls JavaScript method in controller sendDataToComponentB. This function uses fireEvent method in pubsub library and fires a custom event with name carselected. Selected carname is also passed as data in the event payload.

auraComponentB component, has a listener added for carselected event. It is achieved by using registerListener method in auraPubsub utility. Inside handlePubsubReady methos we add a listener using the line registerListener('carselected', callback);. This basically tells "whenever a carselected event is received, go to callback inside handlePubsubReady method in JavaScript controller.

Finally when diplaySelectedCar method is called, we take value from the event payload and assigns to valueGotFromA variable in JavaScript

Things to Note

  • This is a common pattern to pass values between independent aura and lwc components in same page.
  • Make sure that you are using the pubsub and auraPubsub libraries shared above. Otherwise you might get an error pubsub listeners need a "@wire(CurrentPageReference) pageRef" property.

No comments:

Post a Comment