How to make a react component recognize short-cut-keys

Steve Kim
2 min readDec 15, 2019
Photo by Agustinus Nathaniel on Unsplash

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.

  1. 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.
  2. 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”.
  3. 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.
  4. 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”
  5. 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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Steve Kim
Steve Kim

Written by Steve Kim

A Certified Public Accountant / Hobbyist-programmer-but-dead-serious-specializing JavaScript, ReactJS, NextJS, Rust and AWS.

No responses yet

Write a response