Created
September 6, 2023 22:24
-
-
Save felpin/cfb99831fb274101b1cddb40cacda45b to your computer and use it in GitHub Desktop.
Component with an internal ref that syncs with a ref received br arguments
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
import {forwardRef, ForwardRefRenderFunction, MutableRefObject, useRef} from 'react' | |
const _ComponentWithInternalRef: ForwardRefRenderFunction<HTMLDivElement> = (props, ref) => { | |
const internalRef: MutableRefObject<HTMLDivElement | null> = useRef(null) | |
const internalCallbackRef = (element: HTMLDivElement | null) => { | |
internalRef.current = element | |
if (!ref) return | |
if (typeof ref === 'function') { | |
ref(element) | |
} else { | |
ref.current = element | |
} | |
} | |
return <div ref={internalCallbackRef} /> | |
} | |
export const ComponentWithInternalRef = forwardRef(_ComponentWithInternalRef) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment