Skip to content

Instantly share code, notes, and snippets.

@tungd
Last active November 30, 2018 06:33
Show Gist options
  • Select an option

  • Save tungd/8282155 to your computer and use it in GitHub Desktop.

Select an option

Save tungd/8282155 to your computer and use it in GitHub Desktop.
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 registry = {}
window.ReactHelper = {
register: function(name, constructor) {
registry[name] = constructor
},
initComponents: function() {
var i, name, props, selector, names = Object.keys(registry)
for (i = 0; i < names.length; i += 1) {
name = names[i]
selector = '[react-component="'+name+'"],[data-react-component="'+name+'"]'
document.querySelectorAll(selector).forEach(function(node) {
props = node.getAttribute('react-props') ||
node.dataset['reactProps'] || 'null'
React.renderComponent(registry[name](JSON.parse(props)), node)
})
}
}
}
window.addEventListener('DOMContentLoaded', window.ReactHelper.initComponents)
}(window, window.React);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment