The `useAnchoredPosition` hook returns generic refs for Element, which always requires a type assertion by the user
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:
- Update the
useAnchoredPositionhook to take optional type parameters,TAnchorElementandTFloatingElement. These type parameters get passed touseProvidedRefOrCreatein order to get back the correctly-typed ref object, and in turn, returned by theuseAnchoredPositionhook. - Default the new type parameters to HTMLDivElement.
divis likely the most common element type for the floating element, and possibly for anchor as well (the other possibility for anchor would bebutton).
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