0

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>

2 Answers 2

4

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!

Sign up to request clarification or add additional context in comments.

Comments

1

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]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.