Skip to content

Instantly share code, notes, and snippets.

@stphn
Created November 20, 2021 22:26
Show Gist options
  • Save stphn/1715e5dec77e78a51a7a82e89b13dc9f to your computer and use it in GitHub Desktop.
Save stphn/1715e5dec77e78a51a7a82e89b13dc9f to your computer and use it in GitHub Desktop.
How to add keyboard shortcuts to your React app
import { useCallback, useEffect } from 'react';
export default function App() {
// handle what happens on key press
const handleKeyPress = useCallback((event) => {
console.log(`Key pressed: ${event.key}`);
}, []);
useEffect(() => {
// attach the event listener
document.addEventListener('keydown', handleKeyPress);
// remove the event listener
return () => {
document.removeEventListener('keydown', handleKeyPress);
};
}, [handleKeyPress]);
return (
<div>
<h1>Hello world</h1>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment