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.js
to see if splitting the code fromSaveEmployee.js
would fix the issue and to see if it works likedocument.body.addEventListener
, sinceIndex.js
is the main component that houses all children components, but no luck.
2
Answers
onClick
is for handling mouse events. You want to useonKeyPress
(oronKeyUp
oronKeyDown
. Read Q/A: onKeyPress Vs. onKeyUp and onKeyDown).The
event.key
for"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
onCLick
: There no event named like this . ( true you can handle events on the react element withonClick={someFunction}
, but events with usingelement.addEventListener(event)
are not named like that )click
: Mouse click event .keydown
: Keyboard click down event .https://codesandbox.io/s/state-practice-forked-9m7z7j?file=/src/SaveEmployee.js