Dealing with computer with short-cut-keys like “ctrl+c” or “ctrl+v” always makes your life better. It definetly expediates the your work. I was thinking that It would not be that hard to deploy the short-cut-keys functionality to my react-components so I started working on it this morning.
The react component that can recognize three customized short-cut-keys looks like below.
- I used “shift” key to turn on short-cut-mode instead of “ctrl” or “alt” key because my browser already uses “ctrl” or “alt” key for its own short-cut-keys system. By using “shift” key, I could avoid collison with the browser.
- I set up a state of “shortCutMode”, a boolean value. So whenever users press “shift” key, it turns on short-cut-mode and gets ready to receive additional keys like “a”, “b”, or “c”.
- While the short-cut-mode on, if user clicks one of the additional keys, in this case, “a”, “b” or “c”, it executed a function I named “short-cut-action”. I just made one function for all three additional keys but it is up to you to make separate three functions for each. When the function execution ended, I made the short-cut-mode off for next short-cut-key actions.
- In the codesandbox example, try pressing “shift” key. You will see the blue “ShortCutMode is off” change to “ShortCutMode is on”. That means the component is ready to accept an additional key. Then if you press either “a”, “b” or “c”, it executes the short-cut-action function and displays the result on the screen like “shift_A_actuion is executed” or “shift_B_actuion is executed”
- You might want to customize most parts of the exampled component, but the basic logic I adopted is pretty straightforward and easy to use.
Thank you for reading my post. If you have thoughts or better idea on this topic, you are always welcome to leave a comments.