Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to retrieve a component's instance from a React Fiber?

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?

like image 533
fraxture Avatar asked Oct 20 '25 23:10

fraxture


1 Answers

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});
like image 92
Chetabahana Avatar answered Oct 23 '25 13:10

Chetabahana