component-size
component-size copied to clipboard
not working with React.forwardRef
not working with React.forwardRef
You can create an inner ref when the forwarded ref is null
and coerce it to exclude callback refs.
import { ForwardedRef, RefObject, useRef } from 'react'
function useEnsuredRef<T>(ref: ForwardedRef<T>): RefObject<T> {
const defaultRef = useRef<T>(null)
if (typeof ref === 'function') {
throw new Error('callback refs are not supported')
}
return ref === null ? defaultRef : ref
}
export default useEnsuredRef