Selaa lähdekoodia

Add `useKeyPress` hook

cihat 2 vuotta sitten
vanhempi
commit
f4ee701225
1 muutettua tiedostoa jossa 27 lisäystä ja 0 poistoa
  1. 27 0
      src/hooks/useKeyPress.tsx

+ 27 - 0
src/hooks/useKeyPress.tsx

@@ -0,0 +1,27 @@
+import { useState, useEffect } from "react";
+
+const useKeyPress = (targetKey) => {
+  const [keyPressed, setKeyPressed] = useState<boolean>(false);
+  function downHandler({ key }) {
+    if (key === targetKey) {
+      setKeyPressed(true);
+    }
+  }
+  const upHandler = ({ key }) => {
+    if (key === targetKey) {
+      setKeyPressed(false);
+    }
+  };
+  useEffect(() => {
+    window.addEventListener("keydown", downHandler);
+    window.addEventListener("keyup", upHandler);
+
+    return () => {
+      window.removeEventListener("keydown", downHandler);
+      window.removeEventListener("keyup", upHandler);
+    };
+  }, []);
+  return keyPressed;
+};
+
+export default useKeyPress;