How do I fix a React TypeScript error with the return value of useHotkeys hook not matching the type of the div element ref prop

Viewed 266

Following these docs from the react-hotkeys-hook package (https://react-hotkeys-hook.vercel.app/docs/documentation/useHotkeys/scoping-hotkeys), I am trying to scope the registration of some hotkeys to a particular React component. However, the ref object returned by this package's 'useHotkeys' hook causes a TypeScript error when I try to pass it to a via its ref prop. (I can get the hotkeys to work when I don't scope it to a particular component, but this error prevents the code from building.

My hook code:

import { useHotkeys, Options } from 'react-hotkeys-hook';

export const useKeyboardFormSubmit = (
  callback: () => void,
  deps: any[] = [],
) => {
  const hotKeyOptions: Options = {
    enableOnTags: ['INPUT', 'TEXTAREA', 'SELECT'],
  };
  const ref = useHotkeys(
    'ctrl+enter, cmd+enter',
    () => {
      callback();
    },
    hotKeyOptions,
    deps,
  );
  return ref;
};

Excerpt of the React function component:

const EditAccountForm: FC<EditAccountFormProps> = (props) => {
  ...........
  const ref = useKeyboardFormSubmit(() => {
    console.log('contact got keystrokes');
    handleSubmit(onSubmit)();
  });
  ...........
  return (<div ref={ref} tabIndex={-1}>X</div>)

This produces this build error:


TypeScript error in /Users/byofuel/code/monetize-now/platform/frontend/src/routes/Accounts/EditAccountForm.tsx(139,12):
Type 'MutableRefObject<Element | null>' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.
  Type 'MutableRefObject<Element | null>' is not assignable to type 'RefObject<HTMLDivElement>'.
    Types of property 'current' are incompatible.
      Type 'Element | null' is not assignable to type 'HTMLDivElement | null'.
        Type 'Element' is missing the following properties from type 'HTMLDivElement': align, accessKey, accessKeyLabel, autocapitalize, and 108 more.  TS2322

    137 |       )}
    138 |     >
  > 139 |       <div ref={ref}>X</div>
        |            ^

It appears useHotKeys returns a 'MutableRefObject<Element | null>' but for the div element's ref prop, React expects a 'LegacyRef | undefined'.

When I try forcing the type, the code builds but the hotkeys don't work -- code below:

const ref = useKeyboardFormSubmit(() => {
    console.log('contact got keystrokes');
    handleSubmit(onSubmit)();
  }) as LegacyRef<HTMLDivElement>;

Any suggestions greatly appreciated!

1 Answers

reading the docs you can see that the useHotkeys accepts a generic.

function useHotkeys<T extends Element>

so you can fix this error by passing the correct element type

const ref = useHotkeys<HTMLDivElement>(...)
Related