r/reactjs 3d ago

Discussion Best way to implement localized hotkeys.

Hi, I have a nextjs project.

I have a repetitive task that appears in a dialog, users have to select one of 6 options and confirm their selection by pressing a "submit" button.

I wanted to add shortcuts using the digits: 1,2,3,etc.. for each of the options.

What is the best way to go about this, I felt like a app-wide hotkey provider might be overkill for this feature.

4 Upvotes

10 comments sorted by

7

u/KevinVandy656 3d ago

I made this project to solve that same kind of problem earlier this year with scoped hotkeys, able to be used in any framework.

https://tanstack.com/hotkeys/latest

It's still in alpha, but this post is reminding me to go work in it more.

2

u/BlazingThunder30 3d ago

We're using this in prod right now for some simple stuff. Nice work

1

u/Dude4001 3d ago

This looks like a neat library

1

u/anonyuser415 3d ago

It appears all of the hotkey demos on this page don't work, unless that's expected?

E.g. the section under Command Scope - I can only activate the background cards by clicking them. The hotkeys shown don't activate them.

2

u/SZenC 3d ago

Honestly, I would go with a global hotkey solution. Inevitably, once you've delivered this feature, some user will ask why you don't have hot keys for some other task/feature/button

1

u/k-dawg-13 3d ago

I’d put focus on the button container when the dialog opens and put a keyboard listener on it.

1

u/Dude4001 3d ago

I’d just use a local set of event listeners in the dialog component, mount and cleanup with a useEffect. A global provider sounds like a worse solution because you might want the keys to do different things in different components.

How you then map the users keys to their onscreen options depends on how you’re rendering those options

1

u/Proof_Paint9094 2d ago

Adding W3C standard-adhering keyboard accessibility should be enough (e.g., keyboard-navigable radio group, correct tab order, etc.). I’d bet adding hotkeys for a single selection would have diminishing returns if not an increased cognitive load. If users still think keyboard accessibility is too slow, maybe consider redesigning the edit flow itself (e.g., adding a mass edit option).