Created
August 26, 2022 03:12
-
-
Save hijiangtao/bf5826c80598a898baed628e2634050b to your computer and use it in GitHub Desktop.
How to get React FiberNode from DOM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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