Skip to content

Commit

Permalink
feat: Add useEscapeKeyClose custom hook
Browse files Browse the repository at this point in the history
This commit introduces a new custom hook, useEscapeKeyClose. The hook registers a document-wide keyboard listener that, for any 'Escape' key event, invokes a callback function passed into the hook. Notably, this provides a standard and reusable solution for closing components or other UI elements in response to a user pressing the 'Escape' key.
  • Loading branch information
mallikcheripally committed Jul 20, 2024
1 parent 17f56f8 commit f02728b
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/hooks/useEscapeKeyClose.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useEffect } from 'react';

/**
* useEscapeKeyClose
*
* A custom hook to handle the Escape key press event and trigger a callback.
*
* @param {() => void} closeCallback - The callback function to execute on Escape key press.
*/
const useEscapeKeyClose = (closeCallback: () => void) => {
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
closeCallback();
}
};

document.addEventListener('keydown', handleKeyDown);

return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [closeCallback]);
};

export default useEscapeKeyClose;

0 comments on commit f02728b

Please # to comment.