moodist/src/hooks/use-keyboard-button.ts
2024-04-23 23:22:39 +03:30

19 lines
500 B
TypeScript

import { useCallback } from 'react';
import type { KeyboardEvent } from 'react';
export const useKeyboardButton = (
actionCallback: () => void,
): ((event: KeyboardEvent<HTMLElement>) => void) => {
const handleKeyDown = useCallback(
(event: KeyboardEvent<HTMLElement>) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
actionCallback();
event.stopPropagation();
}
},
[actionCallback],
);
return handleKeyDown;
};