useKeyPress.tsx 875 B

1234567891011121314151617181920212223242526272829303132333435
  1. import {useEffect, useState} from 'react';
  2. /**
  3. * Hook to detect when a specific key is being pressed
  4. */
  5. const useKeyPress = (targetKey: string, target?: HTMLElement) => {
  6. const [keyPressed, setKeyPressed] = useState(false);
  7. const current = target ?? document.body;
  8. useEffect(() => {
  9. const downHandler = ({key}: KeyboardEvent) => {
  10. if (key === targetKey) {
  11. setKeyPressed(true);
  12. }
  13. };
  14. const upHandler = ({key}: KeyboardEvent) => {
  15. if (key === targetKey) {
  16. setKeyPressed(false);
  17. }
  18. };
  19. current.addEventListener('keydown', downHandler);
  20. current.addEventListener('keyup', upHandler);
  21. return () => {
  22. current.removeEventListener('keydown', downHandler);
  23. current.removeEventListener('keyup', upHandler);
  24. };
  25. }, [targetKey, current]);
  26. return keyPressed;
  27. };
  28. export default useKeyPress;