Get React Component Data by DOM Node

By  on  

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:

React Element State

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!

Recent Features

Incredible Demos

  • By
    Fancy FAQs with MooTools Sliders: Version 2

    A little over a year ago I authored a post titled Fancy FAQs with MooTools Sliders. My post detailed a method of taking boring FAQs and making them more robust using the world's best JavaScript framework: MooTools. I've taken some time to...

  • By
    9 Incredible CodePen Demos

    CodePen is a treasure trove of incredible demos harnessing the power of client side languages.   The client side is always limited by what browsers provide us but the creativity and cleverness of developers always pushes the boundaries of what we think the front end can do.  Thanks to CSS...

Discussion

  1. Hristo

    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…

  2. The function can be shortened to using latest es6. But not sure if this is best way

    const findReactElement = (node) => node[Object.keys(node).find(key => key.startsWith('__reactInternalInstance$'))]?._debugOwner?.stateNode || null
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!