Created
November 20, 2021 22:26
-
-
Save stphn/1715e5dec77e78a51a7a82e89b13dc9f to your computer and use it in GitHub Desktop.
How to add keyboard shortcuts to your React app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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