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
    dwProgressBar v2:  Stepping and Events

    dwProgressBar was a huge hit when it debuted. For those of you who didn't catch my first post, dwProgressBar is a MooTools 1.2-based progress bar which allows for as much flexibility as possible. Every piece of dwProgressBar can be controlled by CSS...

  • By
    MooTools dwCheckboxes Plugin

    Update / Fix: The checkboxes will no longer toggle when the "mouseup" event doesn't occur on a checkbox. Every morning I wake up to a bunch of emails in my Gmail inbox that I delete without reading. I end up clicking so many damn checkboxes...

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!