Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 381
Santiago Avatar asked Oct 28 '18 16:10

Santiago


People also ask

How do I get the keyboard event in React?

The onKeyPress event in ReactJS occurs when the user presses a key on the keyboard but it is not fired for all keys e.g. ALT, CTRL, SHIFT, ESC in all browsers. To use the onKeyPress event in ReactJS we will use the predefined onKeyPress method.

What is SyntheticEvent in React?

Overview. Your event handlers will be passed instances of SyntheticEvent , a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event, including stopPropagation() and preventDefault() , except the events work identically across all browsers.


1 Answers

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>
like image 189
Tholle Avatar answered Sep 20 '22 03:09

Tholle