Skip to content

Instantly share code, notes, and snippets.

@nadav-dav
Created March 15, 2016 10:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nadav-dav/31771fd024cab5ef0484 to your computer and use it in GitHub Desktop.
Save nadav-dav/31771fd024cab5ef0484 to your computer and use it in GitHub Desktop.
React: Getting a component from a DOM element
let searchRoot = ReactDom.render(React.createElement(Main), document.getElementById('main'));
try {
var getComponent = (comp) => comp._renderedComponent ? getComponent(comp._renderedComponent) : comp;
var getComponentById = (id)=> {
var comp = searchRoot._reactInternalInstance;
var path = id.substr(1).split('.').map(a=> '.' + a);
if (comp._rootNodeID !== path.shift()) throw 'Unknown root';
while (path.length > 0) {
comp = getComponent(comp)._renderedChildren[path.shift()];
}
return comp._instance;
};
window.$r = (node)=> getComponentById(node.getAttribute('data-reactid'))
} catch (e) {
console.info(e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment