Skip to content

Instantly share code, notes, and snippets.

@attitude
Created October 6, 2021 12:59
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 attitude/bf421855b972a23ef939067c2376e04e to your computer and use it in GitHub Desktop.
Save attitude/bf421855b972a23ef939067c2376e04e to your computer and use it in GitHub Desktop.
React: Use forwardRef with useRef
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