aboutsummaryrefslogtreecommitdiff
path: root/src/components/hooks/useEscapeKey.ts
blob: cc1d30892d05b2dab250fcd99df4afe920fda3df (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { type KeyboardEvent, useCallback, useEffect } from 'react';

export function useEscapeKey(handler: (event: KeyboardEvent) => void) {
  const escFunction = useCallback((event: KeyboardEvent) => {
    if (event.key === 'Escape') {
      handler(event);
    }
  }, []);

  useEffect(() => {
    document.addEventListener('keydown', escFunction as any, false);

    return () => {
      document.removeEventListener('keydown', escFunction as any, false);
    };
  }, [escFunction]);

  return null;
}