3

I am trying to traverse through React Component Tree( or somehow get access to all components) and create my own custom UI inside the browser(most likely an extension) to manipulate different components.

this is my code:

// const root_node = root._internalRoot.current; 
const root_node = document.getElementById('root')
const renderer = window.__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.get(1);
const rendered_root_node = renderer.findFiberByHostInstance(root_node);

But it's returning null. I tried using findHostInstanceByFiber as well.

Is there any way to traverse through the components in the browser?

Saif789
  • 69
  • 3
  • 1
    Inspect the source code of *React devtools extension* which shows how to setup this HOOK thing. This is required to receive the info from React, AFAICT. – wOxxOm Jul 26 '22 at 17:30
  • try https://developer.mozilla.org/en-US/docs/Web/API/DOMParser or https://www.npmjs.com/package/html-react-parser – akgaur Jan 17 '23 at 10:46

1 Answers1

1

Here is an example of how you can traverse the React component tree using the renderers property of the __REACT_DEVTOOLS_GLOBAL_HOOK__ object:

function traverseComponentTree(renderer, fiberNode, callback) {
    callback(fiberNode);
  
    let child = fiberNode.child;
    while (child) {
        traverseComponentTree(renderer, child, callback);
        child = child.sibling;
    }
}

const renderer = window.__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.get(1);
const rootFiber = renderer.mounts[0];

traverseComponentTree(renderer, rootFiber, (fiberNode) => {
  console.log(fiberNode.stateNode); // this will give you the instance of the component
  console.log(fiberNode.type); // this will give you the type of the component
});

Please keep in mind that this code is intended for development use only, as the __REACT_DEVTOOLS_GLOBAL_HOOK__ is not available in production mode.

Also, If you are using the latest version of react, it's important to know that the __REACT_DEVTOOLS_GLOBAL_HOOK__ has been removed.

Hossein Rashno
  • 3,073
  • 1
  • 25
  • 49