Reputation: 4518
I can inspect a component's props with the React developer tools. Is it possible to get the component's props from its corresponding HTML element from the console without using the developer tools?
The solution would be something like this:
const someElement = document.querySelector('.some-element')
getElementReactProps(someElement)
I tried to inspect the HTML element's properties __reactFiber$at69yqn7c1k
and __reactProps$at69yqn7c1k
but couldn't find any of its props that I see in the React developer tools.
I have also found other stack overflow threads but none of them worked. (React - getting a component from a DOM element for debugging, React - get React component from a child DOM element?, How do you inspect a react element's props & state in the console?)
Any ideas?
Upvotes: 10
Views: 4011
Reputation: 226
React does seem to store the correct properties in some parent elements, but not in child elements.
The code below works by walking down the path from the given parent to the target child in the react prop tree, after tracing it from the DOM tree. I've only tested it with a single app but I believe it works with all elements created by React 17+.
function getReactProps(parent: Element, target: Element): any {
const keyof_ReactProps = Object.keys(parent).find(k => k.startsWith("__reactProps$"));
const symof_ReactFragment = Symbol.for("react.fragment");
//Find the path from target to parent
let path = [];
let elem = target;
while (elem !== parent) {
let index = 0;
for (let sibling = elem; sibling != null;) {
if (sibling[keyof_ReactProps]) index++;
sibling = sibling.previousElementSibling;
}
path.push({ child: elem, index });
elem = elem.parentElement;
}
//Walk down the path to find the react state props
let state = elem[keyof_ReactProps];
for (let i = path.length - 1; i >= 0 && state != null; i--) {
//Find the target child state index
let childStateIndex = 0, childElemIndex = 0;
while (childStateIndex < state.children.length) {
let childState = state.children[childStateIndex];
if (childState instanceof Object) {
//Fragment children are inlined in the parent DOM element
let isFragment = childState.type === symof_ReactFragment && childState.props.children.length;
childElemIndex += isFragment ? childState.props.children.length : 1;
if (childElemIndex === path[i].index) break;
}
childStateIndex++;
}
let childState = state.children[childStateIndex] ?? (childStateIndex === 0 ? state.children : null);
state = childState?.props;
elem = path[i].child;
}
return state;
}
Example usage:
let itemRow = document.querySelectorAll("#item-row")[2];
let menuBtn = itemRow.querySelector("#more-button");
let props = getReactProps(itemRow, menuBtn);
//This may also work:
let props = getReactProps(menuBtn.parentElement, menuBtn);
Upvotes: 9