react icon indicating copy to clipboard operation
react copied to clipboard

The `useAnchoredPosition` hook returns generic refs for Element, which always requires a type assertion by the user

Open T-Hugs opened this issue 1 year ago • 0 comments

Description

The useAnchoredPosition hook will create refs if they are not passed in. However, when it does so, it creates a generic React.RefObject<Element> ref and returns that. Therefore, when it is used on any JSX node, it must be accompanied by a type assertion, e.g. <div ref={floatingElementRef as React.RefObject<HTMLDivElement>.

This can be fixed by doing 2 things:

  1. Update the useAnchoredPosition hook to take optional type parameters, TAnchorElement and TFloatingElement. These type parameters get passed to useProvidedRefOrCreate in order to get back the correctly-typed ref object, and in turn, returned by the useAnchoredPosition hook.
  2. Default the new type parameters to HTMLDivElement. div is likely the most common element type for the floating element, and possibly for anchor as well (the other possibility for anchor would be button).

This will allow consumers to use the refs returned by the hook without adding on a type assertion. See other codebase changes as an example.

It's possible this is a very minor breaking change: If a consumer is using a type assertion to fit a ref to an element other than a div, this change may break them. The downstream fix is to 1) remove the type assertion, and 2) pass the correct type param into useAnchoredPosition.

Steps to reproduce

function MyComponent() {
  const {anchorElementRef, floatingElementRef, position} = useAnchoredPosition();
  return (
    <div>
        { /* the type assertions below should not be necessary */ }
        <div ref={anchorElementRef as React.RefObject<HTMLDivElement>}>The anchor</div>
        <div ref={floatingElementRef as React.RefObject<HTMLDivElement>}>The floating element</div>
    </div>
  );
}

Version

latest

Browser

No response

T-Hugs avatar Mar 28 '24 15:03 T-Hugs