
Introduction
When you need to listen to a hotkey, you would normally use theonKeyDown event listener.
In twenty-front however, you might have conflicts between same hotkeys that are used in different components, mounted at the same time.
For example, if you have a page that listens for the Enter key, and a modal that listens for the Enter key, with a Select component inside that modal that listens for the Enter key, you might have a conflict when all are mounted at the same time.
The useScopedHotkeys hook
To handle this problem, we have a custom hook that makes it possible to listen to hotkeys without any conflict.
You place it in a component, and it will listen to the hotkeys only when the component is mounted AND when the specified hotkey scope is active.
How to listen for hotkeys in practice?
There are two steps involved in setting up hotkey listening :- Set the hotkey scope that will listen to hotkeys
- Use the
useScopedHotkeyshook to listen to hotkeys
Use cases for hotkeys
In general, you’ll have two use cases that require hotkeys :- In a page or a component mounted in a page
- In a modal-type component that takes the focus due to a user action
Listening to hotkeys in a page
Example :Listening to hotkeys in a modal-type component
For this example we’ll use a modal component that listens for the Escape key to tell its parent to close it. Here the user interaction is changing the scope.What is a hotkey scope?
A hotkey scope is a string that represents a context in which the hotkeys are active. It is generally encoded as an enum. When you change the hotkey scope, the hotkeys that are listening to this scope will be enabled and the hotkeys that are listening to other scopes will be disabled. You can set only one scope at a time. As an example, the hotkey scopes for each page are defined in thePageHotkeyScope enum: