Skip to content

Instantly share code, notes, and snippets.

@anastasiya29
Forked from tungd/react-helper.js
Last active December 1, 2017 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anastasiya29/8574b153b956ddb7abc928c8eaf7839a to your computer and use it in GitHub Desktop.
Save anastasiya29/8574b153b956ddb7abc928c8eaf7839a to your computer and use it in GitHub Desktop.
React Helper to initialize components from HTML. Facilitates React integration with Sitecore renderings.
/**
* react-helper.js
* Source: https://gist.github.com/anastasiya29/8574b153b956ddb7abc928c8eaf7839a
*
* Helper for Facebook's React UI Library. Adds support for declaring
* component from HTML. Adds support for dependency injection.
*
* Usage:
* 1. Register a component with optional dependencies:
* ReactHelper.register('MyComponent', MyComponent, { depName: depFunc })
* 2. Declare the DOM node:
* <div react-component="MyComponent" react-props="{'name':'value'}"
*/
!function(window, React, ReactDOM) {
var domReady = false, registry = {}, queue = [], deps = {};
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, dependencies) {
registry[name] = constructor;
queue.push(name);
if (dependencies) deps[name] = dependencies;
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';
props = JSON.parse(props);
if (deps.hasOwnProperty(name)) {
for (var key in deps[name])
{
if (deps[name].hasOwnProperty(key)) props[key] = deps[name][key];
}
}
ReactDOM.render(React.createElement(registry[name], props), node);
});
}
};
window.addEventListener('DOMContentLoaded', function() {
domReady = true;
ReactHelper.initComponents();
});
}(window, window.React, window.ReactDOM);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment