Handling Keyboard Commands with Redux

Sandro Padin
1 min readJan 6, 2018

--

I recently remembered a pattern I used for handling keyboard commands. It’s fairly straightforward, and thought I’d share how I solved this.

In this scenario, I wanted keyboard commands to trigger Redux actions, but the actions shouldn’t be triggered when an input field is focused. A pretty normal requirement for keyboard commands.

I decided to keep the keyboard availability in the Redux store. When keyboard.available is true keyboard commands will be processed, otherwise ignore the keyboard event. I created two custom elements so far <TextArea/> and <Input/>. They call the takeKeyboard and releaseKeyboard actions, and a reducer toggles keyboard.available between true/false based on those actions.

I made an app to show this in action. When you click into the app below and press a key on your keyboard, the corresponding key will light up. Notice when you click into the input fields, the keys stop lighting up. Click back somewhere in the page to blur focus from the input field and the keys start lighting up again.

Explore the code in the app by clicking the hamburger menu button on the top-left and the blue button in the middle.

The more interesting files to note in the app above are

  • src/ducks/keyboard.js
  • src/TextArea.js
  • src/Input.js

You might notice the <TextArea/> and <Input/> components use a component named <WithKeyboardActions/> and wonder what it does. Instead of having essentially the same code in the connected component for those, I extracted that code and made a component with a render prop that will pass down the takeKeyboard and releaseKeyboard actions already bound to dispatch.

That’s about it. I’m happy to answer any questions in the comments.

--

--

Sandro Padin

Programmer currently working with JavaScript and React. Love figuring out how to make things work.