Search code examples
reactjseventskeyboardkeycreate-react-app

handling `onKeyUp` for a div


I want to handle a key clicked on the keyboard to run a function, I'm trying to do:

<div className="playerContainer" onKeyUp={gameState.toggleCP}></div>

but there is no benefit (the div is scaled on the whole page), also I tried to add the handler to the default App class component, what to do?


Solution

  • as i understand, the problem is that gameState.toggleCP is not being called on keyup event. keyup in order for event handler will be called on an element — element must be in focus.

    TL:DR; add keyup listener onto the document

    if you want to handle keyup event no matter which element is in focus — within React app component do the following:

    import { useCallback, useEffect } from "react";
    
    const gameState = {
      toggleCP: () => {
        // your function instructions
      },
    };
    
    export function MyComponent() {
      const handleKeyUp = useCallback(
        (event) => {
          gameState.toggleCP();
        },
        [gameState.toggleCP]
      );
    
      useEffect(() => {
        document.addEventListener("keyup", handleKeyUp);
        return () => {
          document.removeEventListener("keyup", handleKeyUp);
        };
      }, [handleKeyUp]);
    
      return <div className="playerContainer"></div>;
    }
    
    

    good luck fren!