Get React Component Data by DOM Node
Retrieving a React component's DOM node is fairly simple from within the component itself, but what if you want to work backward: retrieve a component's instance by DOM node? This is a task that the old Dojo Toolkit's Dijit framework allowed with the dijit.byId
method, so it made me think if you could do the same with React. It turns out you can retrieve a component instance by DOM node!
The following function allows you to get a React component instance by DOM node:
function findReactElement(node) { for (var key in node) { if (key.startsWith("__reactInternalInstance$")) { return node[key]._debugOwner.stateNode; } } return null; }
If the node is a React component root, you'll see a load of amazing information, like its props, state, context, refs, list of methods, and more:
Modifying props/state and calling render methods don't appear to actually do anything, so manipulation doesn't look possible from the outside, but it is useful to be able to get the component instance based on DOM node if for nothing other than inspection. Nice!
This is not a good practice in my opinion. What if React change these properties in the next versions? In general this approach seems counter-OOP, it’s like stirring in the gut…
The function can be shortened to using latest es6. But not sure if this is best way