Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

react key press hook

// Hook
function useKeyPress(targetKey) {
  // State for keeping track of whether key is pressed
  const [keyPressed, setKeyPressed] = useState<boolean>(false);
  // If pressed key is our target key then set to true
  function downHandler({ key }) {
    if (key === targetKey) {
      setKeyPressed(true);
    }
  }
  // If released key is our target key then set to false
  const upHandler = ({ key }) => {
    if (key === targetKey) {
      setKeyPressed(false);
    }
  };
  // Add event listeners
  useEffect(() => {
    window.addEventListener("keydown", downHandler);
    window.addEventListener("keyup", upHandler);
    // Remove event listeners on cleanup
    return () => {
      window.removeEventListener("keydown", downHandler);
      window.removeEventListener("keyup", upHandler);
    };
  }, []); // Empty array ensures that effect is only run on mount and unmount
  return keyPressed;
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: how to install chalk in node js 
Javascript :: constant expression contains invalid operations laravel 
Javascript :: jquery get custom attribute 
Javascript :: javascript interview questions for freshers 
Javascript :: reset select2 jquery | clear select2 option value 
Javascript :: delete element javascript 
Javascript :: equality operator javascript 
Javascript :: app bar in react native 
Javascript :: discord.js clear console 
Javascript :: How to set up ejs 
Javascript :: onclick send to email javascript 
Javascript :: append to map javascript 
Javascript :: datepicker min max date 
Javascript :: express session 
Javascript :: Implement stack as an abstract data type using singly linked list and use this ADT for conversion of infix expression to postfix, prefix and evaluation of postfix and prefix expression. 
Javascript :: how to create onclick event on css class js 
Javascript :: find max value in javascript 
Javascript :: how to make a github api using react 
Javascript :: nodejs return value 
Javascript :: How to make HTML input tag only accept numerical values? in jsx 
Javascript :: javascript button click event 
Javascript :: jquery api 
Javascript :: add items to a react array in hooks 
Javascript :: app.js 
Javascript :: discord.js presence update 
Javascript :: mongoose make array required 
Javascript :: setstate array 
Javascript :: const is available in es6 
Javascript :: jquery attribute 
Javascript :: remove first element of array javascript 
ADD CONTENT
Topic
Content
Source link
Name
6+4 =