If you don't need to focus on any element and want to listen to keyboard events, you need to add listener to the window object. Here is the solution for spacebar key be pressed down and key up event of up key
import React, { useRef } from 'react';
function KeyUpHandler() {
const keysPressedDown = useRef({});
useEffect(() => {
window.addEventListener("keydown",
(event) => {
// space
if (event.keyCode == 32) {
keysPressedDown.current[event.keyCode] = true;
}
// up
if (event.keyCode == 38) {
keysPressedDown.current[event.keyCode] = true;
}
}, false);
window.addEventListener("keyup",
event => {
// space
if (event.keyCode == 32) {
keysPressedDown.current[event.keyCode] = false;
}
if (keysPressedDown.current[32] && event.keyCode == 38 &&
keysPressedDown.current[38]) {
// call your function here
console.log(' space and up ');
}
// up
if (event.keyCode == 38) {
keysPressedDown.current[event.keyCode] = false;
}
}, false);
}, []);
return <></>
}