React - get React component from a child DOM element? React - get React component from a child DOM element? reactjs reactjs

React - get React component from a child DOM element?


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.


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});


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.