Using CustomEvent in DX Script Applications

I recently needed to demonstrate how two micro-frontend applications (aka Script Applications) could communicate with each other when deployed on the same DX page.

One micro-frontend was written in React and the other in Angular and I decided to use the CustomEvent constructor to demonstrate this.

The Angular app retrieved a set of items by calling a REST API then displayed the response in a table format. Selecting an item in the table created the CustomEvent, passing the selected object as a parameter. Here’s a code snippet:

// Function to dispatch a custom event with the selected item
select(item: any): void {
  // Create and dispatch a custom event named 'selected-item-event'
  // The event carries the selected item as a JSON string in the 'detail' object
  window.dispatchEvent(
    new CustomEvent('selected-item-event', {
      detail: {
        message: JSON.stringify(item), // Serialize the item to a JSON string
      },
    })
  );
}

The React app listened for this CustomEvent and retrieved data using information in the passed object to call a different REST API. The resulting response was displayed in a card format showing the item details and a map. Here’s a code snippet:

import { useEffect } from 'react';

useEffect(() => {
  // Event handler for the custom 'selected-item-event'
  const handleSelectedItemEvent = (e) => {
    // Safely parse the JSON message from the event's detail object
    // and pass the resulting object to fetchItemData
    fetchItemData(JSON.parse(e.detail.message));
  };

  // Register the event listener when the component mounts
  window.addEventListener('selected-item-event', handleSelectedItemEvent);

  // Cleanup: remove the event listener when the component unmounts
  return () => {
    window.removeEventListener('selected-item-event', handleSelectedItemEvent);
  };
}, []); // Empty dependency array ensures this effect runs only once (on mount)

Hope this is helpful.

9 Likes