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?
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With