Skip to content

Instantly share code, notes, and snippets.

@hijiangtao
Created August 26, 2022 03:12
Show Gist options
  • Save hijiangtao/bf5826c80598a898baed628e2634050b to your computer and use it in GitHub Desktop.
Save hijiangtao/bf5826c80598a898baed628e2634050b to your computer and use it in GitHub Desktop.
How to get React FiberNode from DOM
function getFiberInstance(dom: HTMLElement, traverseUp = 0) {
const key = Object.keys(dom).find((key) => {
return (
key.startsWith("__reactFiber$") || // react 17+
key.startsWith("__reactInternalInstance$")
) // react <17
})
const domFiber = dom[key]
if (domFiber == null) return null
// react <16
if (domFiber._currentElement) {
let compFiber = domFiber._currentElement._owner
for (let i = 0; i < traverseUp; i++) {
compFiber = compFiber._currentElement._owner
}
return compFiber._instance
}
// react 16+
const getCompFiber = (fiber) => {
let parentFiber = fiber.return
while (typeof parentFiber.type == "string") {
parentFiber = parentFiber.return
}
return parentFiber
}
let compFiber = getCompFiber(domFiber)
for (let i = 0; i < traverseUp; i++) {
compFiber = getCompFiber(compFiber)
}
return compFiber.stateNode || compFiber
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment