Skip to content

Latest commit

 

History

History
25 lines (19 loc) · 529 Bytes

listen-for-keyboard-events.md

File metadata and controls

25 lines (19 loc) · 529 Bytes

Listen For Keyboard Events

Category: React

You can add a key listener to a React application with the useEffect hook to handle keyboard events.

Add an event listener for keydown events:

useEffect(() => {
  document.body.addEventListener('keydown', onKeyDown);
  return () => {
    document.body.removeEventListener('keydown', onKeyDown);
  }
});

Handle the keydown event:

const onKeyDown = (event: any) => {
  var key = event.key;
  console.log(`You pressed the key: ${key}`);
}