PROFILE

ReactJS jQuery

Communicate between components (ReactJS)

Communicate between components (ReactJS)

So I've been playing a lot with ReactJS lately and one of the problems I was facing was that I needed to comunicate from one component to another. They had different root components, so I couldn't pass the handlers between them.

When the components can't communicate between any sort of parent-child relationship, the documentation recommends setting up a global event system.

The solution I ended up using was a small snippet but rather elegant. I'm going to rely on JavaScript Events to create a small publish–subscribe pattern.

If you have not used pub/sub before, its a messaging pattern where you have "channels" in which you can subscribe to. Any subscribers of a given channel, gets any publication done to it. Kinda like messengers work (E.G.: whatsapp, facebook, etc.), you subscribe to a conversation and anytime the other participant(s) writes something, you get notified.

With this in mind, JS events work in a similar way so we can take advantage of this. A really quick overview on JavaScript Events: Events are "things" that happen to HTML elements, such as clicks, keypress, a change on an input, and much more. 3 basic things that we can do with events on elements:

  • We can listen to specific events
  • We can stop listening for specific events
  • We can trigger events manually

This gives us the basic pub-sub pattern; subscribe, publish and unsubscribe.

For simplicity's sake, I'll use jQuery to illustrate this:

;(function($, window, document, undefined) {

  'use strict';

  const $object = $({});

  $.subscribe = function() {
    $object.on.apply($object, arguments);
  };

  $.publish = function() {
    $object.trigger.apply($object, arguments);
  };

  $.unsubscribe = function() {
    $object.off.apply($object, arguments);
  };

})($, window, document);

David Walsh has a more usable example with plain JavaScript. The one above, has the limitant that if you have 2(or more) nodes that are subscribed to the event 'foo', if one of them unsubscribes, the 'channel' will be removed for the 2 nodes subscribed to 'foo'.

Here is a small pen showing this working with 3 ReactJS components.

comments powered by Disqus