Life @ NCP

not everyone needs to go outside to have fun

Simplest event system you can use with React.js

A common scenario when dealing with React is inter-component communication, particularly when the components do not share a parent child relationship.

For example, consider the case of a context-dependent header bar action that affects the main content window.

        <AppBar />
        <Content />

Arguably, there are a number of alternative solutions such as providing a callback to the AppBar, and propogate back down to the content (you can invoke component methods directly via a ref), but we’ll focus on the non parent-child case mentioned in the official docs.

It turns out that if you’re using browserify you already have access to an implementation of NodeJS events, so emit away.

    // eventService.js
    'use strict';
    var events = require('events');  
    var eventEmitter = new events.EventEmitter();
    module.exports = eventEmitter;  

    var bus = require('./eventService');
    // caller
    handleAction: function(arg) {  
      bus.emit('addCard', arg);
    // receiver
    componentDidMount: function() {  
      bus.on('addCard', this.addCard);