Guest User

Untitled

a guest
Apr 24th, 2021
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import "./styles.css";
  2.  
  3. import { useEffect, useState, useCallback } from "react";
  4. /**
  5.  * useKeyPress
  6.  * @param {string} key - the name of the key to respond to, compared against event.key
  7.  * @param {function} action - the action to perform on key press
  8.  */
  9. export function useKeypress(key, action) {
  10.   useEffect(() => {
  11.     function onKeyup(e) {
  12.       if (e.key === key) action();
  13.     }
  14.     window.addEventListener("keyup", onKeyup);
  15.     return () => window.removeEventListener("keyup", onKeyup);
  16.     // eslint-disable-next-line react-hooks/exhaustive-deps
  17.   }, [action]);
  18. }
  19.  
  20. export function useKeypress2(key, action) {
  21.   useEffect(() => {
  22.     function onKeyup(e) {
  23.       if (e.key === key) action();
  24.     }
  25.     window.addEventListener("keyup", onKeyup);
  26.     return () => window.removeEventListener("keyup", onKeyup);
  27.     // eslint-disable-next-line react-hooks/exhaustive-deps
  28.   });
  29. }
  30.  
  31.  
  32.  
  33.  
  34. export default function App() {
  35.   const [confirm, setConfirm] = useState(false);
  36.  
  37.   const _confirm = useCallback(() => {
  38.     setConfirm((prev) => !prev);
  39.     console.log(confirm);
  40.   }, [confirm]);
  41.  
  42.   const _confirm2 = () => {
  43.     setConfirm((prev) => !prev);
  44.     console.log(confirm);
  45.   };
  46.  
  47.   useKeypress("Escape", _confirm);
  48.   useKeypress2("z", _confirm2);
  49.  
  50.  
  51.   return (
  52.     <div className="App">
  53.       {confirm.toString()}
  54.     </div>
  55.   );
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment