How to Program Keyboard Shortcuts in JavaScript and React

Welcome to my blog ππ½
I'm a Front-End Developer with a passion for learning!
I write about Programming π©π½βπ» and Productivity Tips β
Search for a command to run...

Welcome to my blog ππ½
I'm a Front-End Developer with a passion for learning!
I write about Programming π©π½βπ» and Productivity Tips β
I think you can use hotkeys to do the same!
This is something I never thought about. It's really nice and I just learnt something new! Thank you, Alyssa Holland! π
Thanks for reading!
Although my experience is primarily with front-end development, my current job is affording me the opportunity to do more full-stack work. Naturally, this meant that I needed to explore the different database GUIs available on the market. Here is a l...

A Note on the Series: Fast Fridays π is a series where you will find fast, short, and sweet tips/hacks that you may or may not be aware of. I will try to provide these (fairly) regularly on Fridays. In this Fast Friday tip, I'll explain how to crea...

Over the past year, Iβve started incorporating a Git GUI into my workflow. I still reach for the terminal about 90% of the time, but Iβve found that a GUI can really shine when it comes to things like viewing diffs, checking stashes, or resolving mer...

Simplifying Branch Management with Git Worktree

With all the AI tools popping up these days, I figured I'd try out some speech-to-text software in an attempt to boost my productivity. I've been hearing a lot about βdeveloping at the speed of thoughtβ, so here's a list of the top speech-to-text sof...

Most applications and programs come packed with keyboard shortcuts that allow you to complete common tasks within their interfaces. Thankfully creating shortcuts within our own projects isn't as difficult as one might think. In this article, I will go over how to create keyboard shortcuts in vanilla JavaScript and how you can take that knowledge and easily implement shortcuts in a React app.
In order to determine which keys a user has pressed, we need to add a listener for the keydown event. The object that gets returned from the keydown event contains a few useful properties that can be leveraged to register a desired shortcut or hotkey.
KeyboardEvent.key
key value would be "ArrowRight." (Check out Keycode.info for a convenient tool that allows you to easily visualize JavaScript's keycodes.)
Since most shortcuts are used in combination with a modifier key it's helpful to know the properties that are available to be able to detect these particular keys.
KeyboardEvent.ctrlKey
Boolean indicating whether or not the CTRL key was pressed.KeyboardEvent.metaKey
true or false depending on if the "Meta" key was pressed. For Macs, this is registered as the CMD key and for Windows computers, this is registered as the "Windows key".There are many more properties available than the ones listed above, but those are some of the more common ones to use. To see an exhaustive list of the possible keyboard event properties check out the full list on MDN.
Now that we know which event properties we need to reference we can begin to pair them together to form a proper shortcut. Because most shortcuts are used in conjunction with a modifier key, we will use the ctrlKey property to create a shortcut that will register CTRL + S and CTRL + C to recreate the common "Save" and "Copy" actions.
Based on the properties we learned about above, the code for registering these shortcuts would look something like this:
window.addEventListener("keydown", (event) => {
/*Allows for a case-insensitive shortcut*/
if(event.ctrlKey && (event.key === "S" || event.key === "s")) {
event.preventDefault();
alert("Save File πΎ");
}
if(event.ctrlKey && (event.key === "C" || event.key === "c")) {
event.preventDefault();
alert("Copy Selection βοΈ");
}
});
View demo in a separate browser or place focus on sandbox and then enter shortcuts
Conveniently, implementing shortcuts within React is actually pretty similar to doing so within vanilla JavaScript. The main difference is that we have to utilize the useEffect hook in order to register the side effect and subsequently remove the event listener as a cleanup when the component unmounts.
For example, if we want to register a keydown handler that gets set when a component mounts, it would look something like this:
useEffect(() => {
const handleKeyDown = (event) => {
if (event.ctrlKey && (event.key === "C" || event.key === "c"))
{
event.preventDefault();
alert("Copy Selection βοΈ");
}
}
window.addEventListener("keydown", handleKeyDown);
return () => { /*removes event listener on cleanup*/
window.removeEventListener("keydown", handleKeyDown);
}
}, [])
As an alternative, if you want to have your keydown handler defined outside of the useEffect because it has its own set of dependencies that it needs to keep track of, you could make use of the useCallback hook and set it up like so:
const handleKeyDown = useCallback((event) => {
if (event.ctrlKey && (event.key === "S" || event.key === "s")) {
event.preventDefault();
alert("Save File πΎ");
}
},[props.someDependency]);
useEffect(() => {
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [handleKeyDown]);
As you can see, programming shortcuts into an application is fairly straightforward. Implementing shortcuts provides convenience for users to be able to complete common actions throughout an application.
If you enjoy what you read, feel free to like this article or subscribe to my newsletter, where I write about programming and productivity tips.
As always, thank you for reading, and happy coding!
Photo by Amy Hirschi on Unsplash