Before v16 of React -- that is, before the introduction of React fibers -- it was possible to take a DOM element and retrieve the React component instance as follows:
const getReactComponent = dom => {
  let found = false;
  const keys = Object.keys(dom);
  keys.forEach(key => {
    if (key.startsWith('__reactInternalInstance$')) {
      const compInternals = dom[key]._currentElement;
      const compWrapper = compInternals._owner;
      const comp = compWrapper._instance;
      found = comp;
    }
  });
  return found || null;
};
This no longer works for React v16, which uses the new Fiber implementation. Specifically, the above code throws an error at the line const comparWrapper = compInternals._owner because there is no _owner property anymore. Thus you cannot also access the _instance. 
My question here is how would we retrieve the instance from a DOM element in v16's Fiber implementation?
You may try the function below (updated to work for React <16 and 16+):
window.FindReact = function(dom) {
    let key = Object.keys(dom).find(key=>key.startsWith("__reactInternalInstance$"));
    let internalInstance = dom[key];
    if (internalInstance == null) return null;
    if (internalInstance.return) { // react 16+
        return internalInstance._debugOwner
            ? internalInstance._debugOwner.stateNode
            : internalInstance.return.stateNode;
    } else { // react <16
        return internalInstance._currentElement._owner._instance;
    }
}
Usage:
var someElement = document.getElementById("someElement");
FindReact(someElement).setState({test1: test2});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With