10 minutes read

React JS Detect Save, Copy Keyboard Shortcuts (Ctrl+S/C/V)

Summary:This post explains how to detect various important keyboard shortcuts such as copy (Ctrl+c), paste (Ctrl+v) and save (Ctrl+s) with React JS.

It is often confusing for beginners to handle keyboard shortcuts in React JS. This article explains the same as a working example.

Here is a code snippet to detect Save and Copy keyboard shortcuts in React JS.

const handleKeyDown = (event)=>{
    event.preventDefault();
    let charCode = String.fromCharCode(event.which).toLowerCase();
    if((event.ctrlKey || event.metaKey) && charCode === 's') {
      alert("CTRL+S Pressed");
    }else if((event.ctrlKey || event.metaKey) && charCode === 'c') {
      alert("CTRL+C Pressed");
    }else if((event.ctrlKey || event.metaKey) && charCode === 'v') {
      alert("CTRL+V Pressed");
    }
}
const item = (
    <div onKeyDown={handleKeyDown} contentEditable={true}>
      Read more at HolyCoders.com
    </div>
);
ReactDOM.render(item, document.getElementById('root'));

Explanation:

React JS has inbuilt onKeyDown event which is very helpful to handle keypress events.

The event parameter contains all the necessary details about the keypress. In this example, we use the same event to extract the information and use the if-else statement to compare that.

Join Our Youtube Channel

Subscribe