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
    5 Ways that CSS and JavaScript Interact That You May Not Know About

    CSS and JavaScript:  the lines seemingly get blurred by each browser release.  They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely.  We have our .js files and our .css, but...

  • By
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

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!