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)
})
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With