Robert A Decker Programming Repository


Notes and articles that will reduce the pain

Simple Communication With React Components via Simple Javascript Events

Robert Decker - Monday, January 29, 2018

Here is a simple example of communication with react components through simple javascript events. I'm presenting this here because of the difficulty I had finding a good example online. Most of the online example had you firing the event on the component itself, or they were using eventing libraries or state libraries like Redux. Sometimes we just want something simple.

I'm using code like this in a Ruby on Rails 5.1 library with the react-rails gem. I have data coming in to the client from an activemq server that the client is communicating with via websockets and javascript. Some of this data is then sent to my react components to update the page.

First, here is a button on the page that fires our custom event. I fire the event on the window element, but it could be fired on a lower element in the DOM and will then bubble up to the window.




And here is our react component. It registers itself to listen to our custom event on the window element. When the event comes in it extracts the message and places it on the page.
window.ExternalEventExample = createReactClass({

    getDefaultProps: function() {
        return {title: "title from component"};
    },

    getInitialState: function() {
        return {title: this.props.title};
    },

    componentDidMount: function() {
        console.log('componentDidMount');
        window.addEventListener("sms-custom-event", this.handleSMSCustomEvent, true);
    },

    componentWillUnmount: function() {
        console.log('componentWillUnmount');
        window.removeEventListener("sms-custom-event", this.handleSMSCustomEvent, true);
    },

    handleSMSCustomEvent: function(e) {
        console.log("sms-custom-event triggered message:" + e.detail.message);
        this.setState({
            title: e.detail.message
        });
    },

    render: function() {
        return 

{this.state.title}

} })
Nice and simple!

The important methods are componentDidMount and componentWillUnmount where we register and deregister our component for the sms-custom-event Event.