3

I would like to have an event listener to detect when command+c is pressed so that I can copy something to the clipboard. How do I listen for multiple keys? I have tried something using useState, useEffect, and document.addEventListener, but it didn't work. Here is my code:

const [metaPressed, setMetaPressed] = useState(false)

  useEffect(() => {
    document.addEventListener('keydown', (e) => {
      
      if (e.key === 'Meta') setMetaPressed(true)
        
    })
  })

  useEffect(() => {
    document.addEventListener('keyup', (e) => {

      if (e.key === 'Meta') setMetaPressed(false)
      
    })
  })
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
BobbyOrr4
  • 352
  • 5
  • 14
  • Not sure but this question can help: [How to detect if multiple keys are pressed at once using JavaScript?](https://stackoverflow.com/questions/5203407/how-to-detect-if-multiple-keys-are-pressed-at-once-using-javascript) – norbitrial Sep 23 '20 at 17:02
  • @HanYolo call what? – BobbyOrr4 Sep 23 '20 at 17:02

3 Answers3

3

This is how you can listen for mentioned key events

useEffect(() => {
  const callback = (event: KeyboardEvent) => {
    // event.metaKey - pressed Command key on Macs
    // event.ctrlKey - pressed Control key on Linux or Windows
    if ((event.metaKey || event.ctrlKey) && event.code === 'KeyC') {
      console.log('Pressed Command/Control + C');
    }
  };
  document.addEventListener('keydown', callback);
  return () => {
    document.removeEventListener('keydown', callback);
  };
}, []);

It's also important to always unsubscribe in React cleanup function.

Note: Do not use event.preventDefault() because that will block all user events like Control + C to copy text and that will be annoying for users.

Jurosh
  • 6,984
  • 7
  • 40
  • 51
2

Does it work?

useEffect(() => {
    document.addEventListener('keydown', (e) => {  
        e.preventDefault();
        if ((e.metaKey || e.ctrlKey) && e.code === 'KeyC') {
            console.log('fire!')
        }  
    })
})
HandDot
  • 322
  • 1
  • 6
0

You can use event.metaKey and event.ctrlKey to watch for special keys in Mac