Responsive 16+ version:
If you need the closest instance of the React component to which the selected DOM element belongs, here is how you can find it (modified from @ Guan-Gui solution):
window.getComponentFromElement = function(el) { for (const key in el) { if (key.startsWith('__reactInternalInstance$')) { const fiberNode = el[key]; return fiberNode && fiberNode._debugOwner && fiberNode._debugOwner.stateNode; } } return null; };
Their trick is to use the _debugOwner property, which is a reference to the FiberNode nearest component, of which the DOM element is a part.
Warning: components that work only in development mode will have the _debugOwner property. This will not work in production mode.
bonus
I created this convenient snippet that you can run in your console so that you can click on any element and get an instance of the React component to which it belongs.
document.addEventListener('click', function(event) { const el = event.target; for (const key in el) { if (key.startsWith('__reactInternalInstance$')) { const fiberNode = el[key]; const component = fiberNode && fiberNode._debugOwner; if (component) { console.log(component.type.displayName || component.type.name); window.$r = component.stateNode; } return; } } });
Yangshun Tay May 6 '18 at 21:58 2018-05-06 21:58
source share