Created
March 15, 2016 10:37
-
-
Save nadav-dav/31771fd024cab5ef0484 to your computer and use it in GitHub Desktop.
React: Getting a component from a DOM element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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