React useKeyPress Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to create a custom React hook called useKeyPress that listens for changes in the pressed state of a given key. This hook will be useful in scenarios where we need to detect whether a specific key is being pressed by the user. We will use the useState and useEffect hooks to handle state and event listeners, respectively.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/conditional_render("`Conditional Rendering`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38392{{"`React useKeyPress Hook`"}} react/conditional_render -.-> lab-38392{{"`React useKeyPress Hook`"}} react/hooks -.-> lab-38392{{"`React useKeyPress Hook`"}} react/use_state_reducer -.-> lab-38392{{"`React useKeyPress Hook`"}} end

React useKeyPress Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

This function listens for changes in the pressed state of a given key. To use it:

  • Call useKeyPress() with the target key as an argument.
  • useKeyPress() returns a boolean value that indicates whether the key is currently pressed.
  • The function uses the useState() hook to create a state variable that holds the pressed state of the given key.
  • It defines two handler functions that update the state variable on key down or key up accordingly.
  • The useEffect() hook and EventTarget.addEventListener() are used to handle the 'keydown' and 'keyup' events.
  • Finally, EventTarget.removeEventListener() is used to perform cleanup after the component is unmounted.
const useKeyPress = (targetKey) => {
  const [isKeyPressed, setKeyPressed] = React.useState(false);

  const handleKeyDown = ({ key }) => {
    if (key === targetKey) setKeyPressed(true);
  };

  const handleKeyUp = ({ key }) => {
    if (key === targetKey) setKeyPressed(false);
  };

  React.useEffect(() => {
    window.addEventListener("keydown", handleKeyDown);
    window.addEventListener("keyup", handleKeyUp);

    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      window.removeEventListener("keyup", handleKeyUp);
    };
  }, [targetKey]);

  return isKeyPressed;
};

Here's an example usage of useKeyPress() in a React component:

const MyApp = () => {
  const isWKeyPressed = useKeyPress("w");

  return <p>The "w" key is {!isWKeyPressed ? "not " : ""}pressed!</p>;
};

ReactDOM.render(<MyApp />, document.getElementById("root"));

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the React useKeyPress Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like