sparksuite / react-accessible-dropdown-menu-hook

A simple Hook for creating fully accessible dropdown menus in React
http://sparksuite.github.io/react-accessible-dropdown-menu-hook
MIT License
112 stars 26 forks source link

Typescript errors when using buttons in dropdown #295

Closed RoelN closed 2 years ago

RoelN commented 2 years ago

Thanks for the accessible component! I have a problem when I'm using a button for the items, for example when looping through the items:

            <ul role="menu">
                {options.map((option, index) => (
                    <li key={option.key}>
                        <button
                            type="button"
                            {...itemProps[index]}
                            onClick={() => setSelectedKey(option.key)}
                        >
                            {option.label}
                        </button>
                    </li>
                ))}
            </ul>

Our Typescript complains about the following:

error TS2322: Type '{ children: string; onClick: () => void; onKeyDown: (e: KeyboardEvent<HTMLAnchorElement>) =>
 void; tabIndex: number; role: string; ref: RefObject<HTMLAnchorElement>; type: "button"; }' is not assignable to type 'DetailedHTMLProps<ButtonHTMLAttr
ibutes<HTMLButtonElement>, HTMLButtonElement>'.
  Type '{ children: string; onClick: () => void; onKeyDown: (e: KeyboardEvent<HTMLAnchorElement>) => void; tabIndex: number; role: string; ref: RefObjec
t<HTMLAnchorElement>; type: "button"; }' is not assignable to type 'ClassAttributes<HTMLButtonElement>'.
    Types of property 'ref' are incompatible.
      Type 'RefObject<HTMLAnchorElement>' is not assignable to type 'LegacyRef<HTMLButtonElement> | undefined'.
        Type 'RefObject<HTMLAnchorElement>' is not assignable to type 'RefObject<HTMLButtonElement>'.
          Type 'HTMLAnchorElement' is missing the following properties from type 'HTMLButtonElement': disabled, form, formAction, formEnctype, and 11 mo
re.

It's currently disabled by disabling the linter (yech!) like so:

{/*eslint-disable-next-line @typescript-eslint/ban-ts-comment*/}
{/* @ts-ignore: */}

But I'd like to do this cleanly. Any advice would be greatly appreciated.

corymharper commented 2 years ago

Hi @RoelN we have an open issue to support further element types for menu items, but in the v1 implementation we only supported anchor tags.

Here's the issue at question, if you'd be interested in contributing it, let us know! https://github.com/sparksuite/react-accessible-dropdown-menu-hook/issues/174

The implemention would probably be quite similar to the changes recently made in https://github.com/sparksuite/react-accessible-dropdown-menu-hook/pull/290.

RoelN commented 2 years ago

Thanks, sorry I missed the open issue. I'd love to promise to submit a PR, but in all honesty it will probably be buried under all my other good intentions.

Thanks again for the useful hook!