useKeyPress.tsx 1.2 KB

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