Reputation: 520
I want to detect key press on whole website that is to listen keypress globally. I tried adding onKeyDown property on div in react but it doesn't catch global event
<div onKeyPress={(e) => console.log(e)}>
<MainLayout visualizerMode={true} />
</div>
Upvotes: 0
Views: 2707
Reputation: 344
You should use destructor, otherwise You will duplicate events with component re-render.
const doStuff = useCallback(
(e: KeyboardEvent) => {
{....}
},
[],
);
useEffect(() => {
document.addEventListener('keydown', doStuff);
return () => {
document.removeEventListener('keydown', doStuff);
};
}, [doStuff]);
Upvotes: 0
Reputation: 520
This can be achieved by listening to onKeyDown
type event, in document object.
Add this to your react component:
useEffect(() => {
document.addEventListener('keydown', (e: KeyboardEvent) => console.log(e))
}, [])
Hope, it's helpful!
Upvotes: 3