React - get React component from a child DOM element?

I'd like to be able to figure out what React component is associated with a certain DOM element.

For example, say I have a div, and I'm rendering my entire application using React. The div has to be rendered by a React component - but which one?

I know that React supplies the method "getDOMNode" to get the DOM node associated with a React component, but I'd like to do the opposite.

Is this possible?

Answers:

Answer

No.

A central concept in React is that you don't actually have a control in the DOM. Instead, your control is that factory function. What's in the DOM is the current render of the control.

If you actually need this, you can keep an object as a global variable, whose keys are the string representations of the names of factory functions, and whose values are the factory functions, then on your renderable div, keep an attribute containing the name of the factory function.

But chances are this is a question of the XY problem (needing X, seeing a way with Y, then asking how to do Y.) Probably if you'd explain your goal there's a better way that better fits React's top-down conceptual model.

Generally speaking, asking to get access to the control from its render is like asking to get access to an SVG from its cached PNG render. It's possible, but it's usually a red flag that something else is conceptually wrong.

Answer

Here's what I use, with React 15.3.0:

window.FindReact = function(dom) {
    for (var key in dom) {
        if (key.startsWith("__reactInternalInstance$")) {
            var compInternals = dom[key]._currentElement;
            var compWrapper = compInternals._owner;
            var comp = compWrapper._instance;
            return comp;
        }
    }
    return null;
};

And then to use it:

var someElement = document.getElementById("someElement");
FindReact(someElement).setState({test1: test2});
Answer

If your situtation demands getting react element from DOM node, here is an approach, "Communicate via event and call back"

You shall fire a custom event on DOM element and have event listener for that custom event in React component. This will map DOM element back to react component.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.