Listens for changes in the pressed state of a given key.
useState()
hook to create a state variable that holds the pressed state of the given key.useEffect()
hook and EventTarget.addEventListener()
to handle the 'keydown'
and 'keyup'
events.EventTarget.removeEventListener()
to perform cleanup after the component is unmounted.const useKeyPress = targetKey => {
const [keyPressed, setKeyPressed] = React.useState(false);
const downHandler = ({ key }) => {
if (key === targetKey) setKeyPressed(true);
};
const upHandler = ({ key }) => {
if (key === targetKey) setKeyPressed(false);
};
React.useEffect(() => {
window.addEventListener('keydown', downHandler);
window.addEventListener('keyup', upHandler);
return () => {
window.removeEventListener('keydown', downHandler);
window.removeEventListener('keyup', upHandler);
};
}, []);
return keyPressed;
};
const MyApp = () => {
const wPressed = useKeyPress('w');
return <p>The "w" key is {!wPressed ? 'not ' : ''}pressed!</p>;
};
ReactDOM.render(<MyApp />, document.getElementById('root'));
React, Hooks
Observes visibility changes for a given element.
React, Hooks
Adds an event listener for the specified event type on the given element.
React, Hooks
Tracks the browser's location hash value, and allows changing it.