Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
T-Hugs opened this issue Mar 28, 2024 · 0 comments · May be fixed by #4448
Labels
bug Something isn't working react

Comments

@T-Hugs
Copy link
Contributor

T-Hugs commented Mar 28, 2024

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 T-Hugs added the bug Something isn't working label Mar 28, 2024
@T-Hugs T-Hugs linked a pull request Mar 28, 2024 that will close this issue
13 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working react
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant