Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React Helper to initialize the component from HTML, similar to AngularJS.
/**
* react-helper.js
*
* Helper for Facebook's React UI Library. Add support for declare
* component on DOM (similar to AngularJS Directive).
*
* Usage:
* - Register a component:
* ReactHelper.register('MyComponent', MyComponent)
* - Declare the DOM node:
* <div react-component="MyComponent" react-props="{'name':'value'}"
* - There is no step 3!
*/
!function(window, React) {
var domReady = false, registry = {}, queue = [];
window.ReactHelper = {
initComponents: function() {
for (var i = 0; i < queue.length; i += 1) {
this.initComponent(queue[i])
}
},
forceInitComponents: function() {
queue = queue.concat(Object.keys(registry));
this.initComponents();
},
register: function(name, constructor) {
registry[name] = constructor;
queue.push(name);
if (domReady) this.initComponents();
},
initComponent: function(name) {
var props, selector =
'[react-component="'+name+'"],[data-react-component="'+name+'"]';
document.querySelectorAll(selector).forEach(function(node) {
props = node.getAttribute('react-props') ||
node.getAttribute('data-react-props') || 'null';
React.renderComponent(registry[name](JSON.parse(props)), node);
})
}
};
window.addEventListener('DOMContentLoaded', function() {
domReady = true;
ReactHelper.initComponents();
});
}(window, window.React);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment