raghav-wd
raghav-wd

Reputation: 520

Detect keypress globally in react typescript?

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

Answers (2)

user3765649
user3765649

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

raghav-wd
raghav-wd

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

Related Questions