group | package | category | title | order | slug | description | import | docs | source |
---|---|---|---|---|---|---|---|---|---|
mantine-hooks |
@mantine/hooks |
dom |
use-hotkeys |
1 |
/hooks/use-hotkeys/ |
Listen for keys combinations on document element |
import { useHotkeys } from '@mantine/hooks'; |
hooks/use-hotkeys.mdx |
mantine-hooks/src/use-hotkeys/use-hotkeys.ts |
import { HooksDemos } from '@mantine/demos';
use-hotkeys accepts as its first argument an array of hotkeys and handler tuples:
hotkey
- hotkey string e.g.ctrl+E
,shift+alt+L
,mod+S
handler
- event handler called when given combination was pressedoptions
- object with extra options for hotkey handler
The second argument is a list of HTML tags:
tagsToIgnore
- HTML tag names that hotkeys will not trigger on
import { useHotkeys } from '@mantine/hooks';
function Demo() {
// ctrl + J and ⌘ + J to toggle color scheme
// ctrl + K and ⌘ + K to search
useHotkeys([
['mod+J', () => console.log('Toggle color scheme')],
['ctrl+K', () => console.log('Trigger search')],
['alt+mod+shift+X', () => console.log('Rick roll')],
]);
return null;
}
use-hotkeys hook can work only with document element, you will need to create your own event listener
if you need to support other elements. For this purpose package exports getHotkeyHandler
function
which should be used with onKeyDown
:
With getHotkeyHandler
you can also add events to any dom node using .addEventListener
:
import { getHotkeyHandler } from '@mantine/hooks';
document.body.addEventListener(
'keydown',
getHotkeyHandler([
['mod+Enter', () => console.log('Submit')],
['mod+S', () => console.log('Save')],
])
);
mod+S
– detects⌘+S
on macOS andCtrl+S
on Windowsctrl+shift+X
– handles multiple modifiersalt + shift + L
– you can use whitespace inside hotkeyArrowLeft
– you can use special keys using this format
function useHotkeys(
hotKeyItem: Array<
[
hotkey: string,
handler: (event: KeyboardEvent) => void,
options?: { preventDefault?: boolean }
]
>
): void;