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

  • By
    Welcome to My New Office

    My first professional web development was at a small print shop where I sat in a windowless cubical all day. I suffered that boxed in environment for almost five years before I was able to find a remote job where I worked from home. The first...

  • By
    9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

Incredible Demos

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!