Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Debug react component
(() => {
const getSelector = target => {
const tag = target.tagName.toLowerCase();
const classSelector = Array.from(target.classList)
.map(_ => '.' + _)
.join('')
const idSelector = target.id ? ('#' + target.id) : '';
return tag + idSelector + classSelector;
}
const getAllParents = target => {
var a = target;
var els = [];
while (a) {
els.unshift(a);
a = a.parentNode;
}
return els;
}
FindReact = function(dom) {
for (var key in dom)
if (key.startsWith("__reactInternalInstance$")) {
var compInternals = dom[key]._currentElement;
var compWrapper = compInternals._owner;
var comp = compWrapper._instance;
return comp;
}
return null;
}
const el = document.createElement('div');
el.id = 'react-component-debug';
el.style.position = 'fixed';
el.style.zIndex = '99999';
el.style.bottom = '0';
el.style.right = '0';
el.style.background = 'white';
el.style.padding = '10px';
document.body.appendChild(el);
document.body.addEventListener('mousemove', function (e) {
const str = getAllParents(e.target)
.map(element => ({
element,
react: FindReact(element),
}))
.filter(_ => _.react)
// .map(_ => {
// debugger;
// return _;
// })
.map(_ => ({
reactName: _.react.constructor.name,
source: (
(_.react._reactInternalInstance._currentElement._source || {})
.fileName || ''
).slice(-50),
selector: getSelector(_.element),
}))
.map(_ => `
<div>${_.selector}(<b>${_.reactName}</b>)</div>
<div>...${_.source}</div>
`)
.join('');
document.getElementById('react-component-debug').innerHTML = str;
}, false);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.