Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event listener for multiple keys in React?

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)
      
    })
  })
like image 608
BobbyOrr4 Avatar asked Oct 27 '25 15:10

BobbyOrr4


1 Answers

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.

like image 170
Jurosh Avatar answered Oct 29 '25 03:10

Jurosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!