Skip to content

Commit

Permalink
[hooks] helper hooks
Browse files Browse the repository at this point in the history
Topic: helper-hooks
Relative: more-input-checks
  • Loading branch information
droneshire committed Apr 16, 2023
1 parent eeba8a5 commit 7cf9077
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/hooks/Events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { RefObject, useCallback, useEffect } from "react";

export const useKeyPress = (
targetKeys: string[],
handler: (event: KeyboardEvent) => void,
ref?: RefObject<HTMLElement>
) => {
const wrappedHandler = useCallback(
(event: KeyboardEvent) => {
if (targetKeys.includes(event.key)) {
handler(event);
}
},
[targetKeys, handler]
);
useEffect(() => {
const currentRef = ref?.current;
if (currentRef) {
currentRef.addEventListener("keydown", wrappedHandler);
} else {
window.addEventListener("keydown", wrappedHandler);
}
return () => {
if (currentRef) {
currentRef.removeEventListener("keydown", wrappedHandler);
} else {
window.removeEventListener("keydown", wrappedHandler);
}
};
}, [wrappedHandler, ref]);
};

0 comments on commit 7cf9077

Please sign in to comment.