简体   繁体   中英

How can I traverse React Component Tree just using __REACT_DEVTOOLS_GLOBAL_HOOK__

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?

Here's an example of how you could traverse the component tree and access the component instances:

// make sure the React Developer Tools extension is installed
const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;

// traverse the component tree
hook.getFiberRoots((roots) => {
  roots.forEach((root) => {
    traverse(root.current);
  });
});

function traverse(fiber) {
  console.log(fiber.stateNode); // logs the component instance
  fiber.child && traverse(fiber.child);
  fiber.sibling && traverse(fiber.sibling);
}

The above example uses the getFiberRoots method on the REACT_DEVTOOLS_GLOBAL_HOOK object to get an array of the roots of the component tree. It then loops through the roots and call traverse function which will traverse the component tree and logs the component instance.

It is worth noting that this feature may be changed in the future and it might not work in all environments and also this is not recommended to use in production.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM