Reputation: 95
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?
Upvotes: 9
Views: 3272
Reputation: 41
This will do the same as Tholle answer example but using React Hooks.
import {useState, useEffect} from 'react';
function App(){
const [lastPressedKey, setLastPressedKey] = useState(null);
const handleKeyPress = (event) => setLastPressedKey(event.key);
useEffect(() => {
window.addEventListener("keydown", handleKeyPress);
return () => window.removeEventListener("keydown", handleKeyPress);
}, []);
return <div>Key last pressed: {lastPressedKey}</div>
}
Upvotes: 4
Reputation: 112787
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>
Upvotes: 7