Skip to content

Commit 4cc29ad

Browse files
committed
[devtools-snippet] add reactHelpers.js
1 parent 8ac8984 commit 4cc29ad

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

devtools-snippets/reactHelpers.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// reactHelpers.js
2+
// https://github.com/0xdevalias/userscripts/tree/main/devtools-snippets
3+
//
4+
// See also:
5+
// - https://gist.github.com/search?q=user:0xdevalias+react
6+
// - https://gist.github.com/0xdevalias/8c621c5d09d780b1d321bfdb86d67cdd#react-internals
7+
8+
// Function to get find all elements connected to React
9+
function findAllReactElements(customPredicate = () => true, rootNode = document, tagQuery = '*') {
10+
if (typeof customPredicate !== 'function') throw 'customPredicate must be a function returning a boolean'
11+
if (typeof rootNode?.['querySelector'] !== 'function') return [];
12+
13+
const foundElements = rootNode.getElementsByTagName(tagQuery);
14+
return Array.from(foundElements).filter(element => {
15+
const keys = Object.getOwnPropertyNames(element);
16+
const reactPropsKey = keys.find(key => key.startsWith('__reactProps$'));
17+
const reactFiberKey = keys.find(key => key.startsWith('__reactFiber$'));
18+
const props = reactPropsKey ? element[reactPropsKey] : null;
19+
const fiber = reactFiberKey ? element[reactFiberKey] : null;
20+
21+
return (props || fiber) && customPredicate({ props, fiber, element });
22+
});
23+
}
24+
25+
// Function to get React props for a given HTML element
26+
function getReactProps(element) {
27+
const propsKey = Object.getOwnPropertyNames(element).find(propName =>
28+
propName.startsWith('__reactProps$')
29+
);
30+
return propsKey ? element[propsKey] : null;
31+
}
32+
33+
// Function to get React fiber for a given HTML element
34+
function getReactFiber(element) {
35+
const fiberKey = Object.getOwnPropertyNames(element).find(propName =>
36+
propName.startsWith('__reactFiber$')
37+
);
38+
return fiberKey ? element[fiberKey] : null;
39+
}

0 commit comments

Comments
 (0)