Created
October 6, 2021 12:59
-
-
Save attitude/bf421855b972a23ef939067c2376e04e to your computer and use it in GitHub Desktop.
React: Use forwardRef with useRef
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 { ForwardedRef, MutableRefObject, useEffect, useRef } from 'react' | |
function useOuterRef(outerRef: ForwardedRef<HTMLElement | null>): MutableRefObject<HTMLElement | null> { | |
const innerRef = useRef<HTMLElement | null>(null) | |
useEffect(() => { | |
if (!outerRef) return | |
if (typeof outerRef === 'function') { | |
outerRef(innerRef.current) | |
} else { | |
outerRef.current = innerRef.current | |
} | |
}, [outerRef]) | |
return innerRef | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment