Closed ZacharyFolk closed 1 year ago
import React, { useState } from 'react';
function KeyCodeObserver() {
const [keyCode, setKeyCode] = useState(null);
const handleKeyDown = (event) => {
if (event.keyCode === 17) { // CTRL key
setKeyCode(17);
} else if (event.keyCode === 32) { // SPACE key
setKeyCode(32);
} else if (event.keyCode === 13) { // ENTER key
setKeyCode(13);
}
}
const handleYClick = () => {
document.addEventListener('keydown', handleKeyDown);
}
return (
<div>
<button onClick={handleYClick}>Y</button>
<div>
{keyCode === 17 && <div style={{backgroundColor: 'red'}}>CTRL</div>}
{keyCode === 32 && <div style={{backgroundColor: 'green'}}>SPACE</div>}
{keyCode === 13 && <div style={{backgroundColor: 'blue'}}>ENTER</div>}
</div>
</div>
);
}
export default KeyCodeObserver;
https://jservice.io/