I would like to listen to keyDown events, specifically, the key S so users can easily save a randomly generated employee conveniently instead of clicking the Save Employee button multiple times.
In JavaScript, I would add the event on the document body like, document.body.addEventListener('keydown'), but in React I don't know where to place the event. For now, I added it inside the index.js file like:
onKeyDown={handleKeyDown}
I commented out my failed attempt (check image, code repo, or snippet below).
function SaveEmployee({ ...props }) {
const [employees, setEmployees] = useState([]);
const displayEmployee = () => {
setEmployees((current) => [...current, { ...props }]);
};
// const displayEmployee = (event) => {
// if (event.key === "KeyS") { setEmployees((current) => [...current, { ...props }]);
// } else { console.log('do nothing'); }
// };
return (
<>
<div>
<button title="Save new random employee data" onClick={displayEmployee}>
Save Employee
</button>
</div>
...
- The keyCode property is deprecated so I tried the event.key but no luck yet.
- I also tried creating a separate component
KeyDownEvents.jsto see if splitting the code fromSaveEmployee.jswould fix the issue and to see if it works likedocument.body.addEventListener, sinceIndex.jsis the main component that houses all children components, but no luck.

onClickis for handling mouse events. You want to useonKeyPress(oronKeyUporonKeyDown. Read Q/A: onKeyPress Vs. onKeyUp and onKeyDown).The
event.keyfor"S"is not"KeyS", it is simply"s"(or"S"if you want it to beshift+s)NOTE: that this event only fires if you have the
<button>in focus.View on CodeSandbox