Skip to content

Instantly share code, notes, and snippets.

@felpin
Created September 6, 2023 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felpin/cfb99831fb274101b1cddb40cacda45b to your computer and use it in GitHub Desktop.
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
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