Search code examples
reactjsaddeventlistener

Global keyboards events on React


I'm making a small drum machine on React, and my idea is that when I press a key on the keyboard a specific sound is played depending which key was pressed. The problem I have is that I want the onKeyPress or onKeyDown event working on window scope, because if I put the event listener on an specific component that component has to be on focus to listen the event. How can I do it?


Solution

  • You can add a keydown listener on the window in the componentDidMount of your topmost component.

    Example

    class App extends React.Component {
      state = { lastPressedKey: null };
    
      componentDidMount() {
        window.addEventListener("keydown", this.handleKeyPress);
      }
    
      componentWillUnmount() {
        window.removeEventListener("keydown", this.handleKeyPress);
      }
    
      handleKeyPress = event => {
        this.setState({ lastPressedKey: event.key });
      };
    
      render() {
        return <div>Key last pressed: {this.state.lastPressedKey}</div>;
      }
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="root"></div>