Skip to content

Idea/Request: Add global 3rd party extension point to the React object #2598

@dougmartin

Description

@dougmartin

tl/dr: Add an empty bare object called 'x' as a new member of the React object so that 3rd party React tools have a global extension point.

I have a couple of internal tools I use with React that I would like to open source. Both tools use a singleton object that is referenced and/or modified by components.

I know I could create the object in the root component and pass it down as a prop but the child components may modify the object and that violates the idea of props being read-only. It also means that if another person open sources a component which uses either of my tools that the user of the component must create that root object in their app and then wire it up down the component tree.

To keep things clean I would love to have a 3rd party extension space hanging off the React object that I could attach my tool's "globals" to so that all the components would have access to it given that they all share the same React global. My suggestion is just to name it "x" and make it a bare object. The documentation would encourage users to then add their own namespace to the object.

Here are is very simple example that adds a 3rd party global event bus to a blogging app using EventEmitter which could be used both on the server and on the client via Browserify.

In app.js (the root component):

require('react-x-event');

React.x.event.bus.on('createPost', ...)

In react-x-event.js

var events = require('events');
React.x.event = {
  bus: new events.EventEmitter(),
  handle: function (e, event, data) {
    e.preventDefault();
    React.x.event.bus.emit(event, data)
  }
}

In new-post.js (a component view shown at some point by a sub-component of app.js)

createPost: function(e) {
  React.x.event.handle(e, 'createPost', ...)
}

render: function () {
  return <form>
    ...
   <button onClick={this.createPost}>Create</button>
  </form>;
}

Without getting lost in the weeds arguing if a global event bus is a good idea for React you can see in this example that I didn't need to wire up the component tree with the bus to allow the sub-component to send a message.

There is nothing from stopping me or anyone else from just globally patching the React object to add the x member but I think it would be better to have it "blessed" and added to the React code so that there are no conflicts in the future over that member name. I also think having a common name like 'x' will allow 3rd party module names to announce how they work, eg require('react-x-event').

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions