Skip to content

Instantly share code, notes, and snippets.

@kmdavis
Created July 5, 2019 15:33
Show Gist options
  • Save kmdavis/1254ad9420ec1cb36784560434028e71 to your computer and use it in GitHub Desktop.
Save kmdavis/1254ad9420ec1cb36784560434028e71 to your computer and use it in GitHub Desktop.
function getReactInstancesForNode (node, { firstOnly } = {}) {
const key = Object.keys(node).find(key => key.startsWith("__reactInternalInstance$"));
let inst = node[key];
const results = [];
while (inst) {
if (typeof inst.elementType === "function") {
const result = {
type: inst.elementType,
};
if (inst.stateNode) {
// NOTE: stateless components have no instance
result.instance = inst.stateNode;
}
if (inst.memoizedProps) {
result.props = inst.memoizedProps;
}
if (inst.memoizedState) {
// NOTE: stateless components have no instance
result.state = inst.memoizedState;
}
if (firstOnly) {
return result;
}
results.push(result);
}
inst = inst.return;
}
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment