component-size icon indicating copy to clipboard operation
component-size copied to clipboard

not working with React.forwardRef

Open MaxmaxmaximusGitHub opened this issue 4 years ago • 1 comments

not working with React.forwardRef

MaxmaxmaximusGitHub avatar Apr 26 '20 21:04 MaxmaxmaximusGitHub

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

caasi avatar May 30 '22 17:05 caasi