Created
January 11, 2025 18:37
-
-
Save agurtovoy/0201718e7cda82b705968207190e6929 to your computer and use it in GitHub Desktop.
Using `react-reconciler` to reimplement `findDOMNode`
This file contains hidden or 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
import { Component } from 'react' | |
//@ts-ignore | |
import { findCurrentHostFiber } from 'react-reconciler/reflection' | |
// https://github.com/facebook/react/blob/main/packages/shared/ReactInstanceMap.js#L18 | |
export function getInstance(key: any) { | |
return key._reactInternals | |
} | |
// https://github.com/facebook/react/blob/main/packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js#L167 | |
type PublicInstance = Element | Text | |
// https://github.com/facebook/react/blob/main/packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js#L322 | |
function getPublicInstance(instance: PublicInstance): PublicInstance { | |
return instance | |
} | |
// https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactFiberReconciler.js#L153 | |
function findHostInstance(component: Component): PublicInstance | null { | |
const fiber = getInstance(component) | |
if (fiber === undefined) { | |
if (typeof component.render === 'function') { | |
throw new Error('Unable to find node on an unmounted component.') | |
} else { | |
const keys = Object.keys(component).join(',') | |
throw new Error(`Argument appears to not be a ReactComponent. Keys: ${keys}`) | |
} | |
} | |
const hostFiber = findCurrentHostFiber(fiber) | |
if (hostFiber === null) { | |
return null | |
} | |
return getPublicInstance(hostFiber.stateNode) | |
} | |
// https://github.com/facebook/react/blob/main/packages/react-dom/src/client/ReactDOMClient.js#L43 | |
export function findDOMNode(componentOrElement: Component<any, any>): null | Element | Text { | |
return findHostInstance(componentOrElement) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment