useKeyboard hook

import { RefObject, useEffect } from 'react';

/**
 * useKeyboardEvent
 */
function useKeyboardEvent<T extends HTMLElement = HTMLElement>({
  ref,
  key,
  condition,
  callback,
}: {
  ref?: RefObject<T>;
  key: string;
  condition: boolean;
  callback: () => void;
}): void {
  useEffect(() => {
    if (condition) {
      const handler = function(event: KeyboardEvent) {
        if (event.key === key) {
          callback();
        }
      };

      const targetEl = ref ? ref.current : window;
      if (targetEl) {
        targetEl.addEventListener('keydown', handler as EventListener);

        return () => {
          targetEl.removeEventListener('keydown', handler as EventListener);
        };
      }
    }
  }, [condition, callback, key, ref]);
}

export default useKeyboardEvent;
#code

© 2021. All rights reserved.

Enjoy the rest of your Thursday.