Skip to content

Instantly share code, notes, and snippets.

@PhilippIRL
Created May 25, 2025 23:55
Show Gist options
  • Save PhilippIRL/2d36dde434b44160e4795fbf5edf60e7 to your computer and use it in GitHub Desktop.
Save PhilippIRL/2d36dde434b44160e4795fbf5edf60e7 to your computer and use it in GitHub Desktop.
function findReactRootFiber() {
const potentialElements = [...document.querySelectorAll("div, :root"), document]
let fiber = null
for(const elem of potentialElements) {
const key = Object.keys(elem).filter(key => key.startsWith("__reactContainer$") || key.startsWith("__reactFiber$"))[0]
if(key) {
fiber = elem[key]
break
}
}
while(fiber.return) {
fiber = fiber.return
}
return fiber
}
function findFirstUsableComponent(fiber, isAlternate=false) {
while(fiber?.child) {
fiber = fiber.child
//if(fiber.type instanceof Function || [0, 1, 6].includes(fiber.tag)) {
if(fiber.tag === 0) { // only use function components
return fiber
}
}
return fiber.alternate && !isAlternate ? findFirstUsableComponent(fiber.alternate, true) : null // if we are just past the first render child does only exist on alternate
}
const rootFiber = findReactRootFiber()
const first = findFirstUsableComponent(rootFiber)
const comp = () => "test" // using this component as root component when then root is window.document is only possible with react 19+, because older react versions dont autocreate html and body/head tags
first.tag = 0
first.type = comp
first.alternate = null // force react to recreate the fiber
first.pendingProps = {} // force a rerender of this component
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment