use-hotkeys

Listen for keys combinations on document element
Import

Usage

Hook accepts an array with hotkey and handler tuples:

  • hotkey - hotkey string e.g. ctrl+E, shift+alt+L, mod+S
  • handler - event handler called when given combination was pressed
import { useHotkeys } from '@mantine/hooks';
function Demo() {
// ctrl + J and ⌘ + J to toggle color scheme
// ctrl + K and ⌘ + K to search
useHotkeys([
['mod+J', () => toggleColorScheme()],
['ctrl+K', () => search()],
['alt+mod+shift+X', () => rickRoll()],
]);
return null;
}

Targeting elements

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 getHotkeysHandler function which should be used with onKeyDown:

import { useState } from 'react';
import { getHotkeyHandler } from '@mantine/hooks';
import { useNotifications } from '@mantine/notifications';
import { TextInput } from '@mantine/core';
function Demo() {
const [value, setValue] = useState("I've just used a hotkey to send a message");
const notifications = useNotifications();
const handleSubmit = () =>
notifications.showNotification({ title: 'Your message', message: value });
const handleSave = () =>
notifications.showNotification({ title: 'You saved', color: 'teal', message: value });
return (
<TextInput
placeholder="Your message"
label="Press ⌘+Enter or Ctrl+Enter when input has focus to send message"
value={value}
onChange={(event) => setValue(event.target.value)}
onKeyDown={getHotkeyHandler([
['mod+Enter', handleSubmit],
['mod+S', handleSave],
])}
/>
);
}

Supported formats

  • mod+S – detects ⌘+S on macOS and Ctrl+S on Windows
  • ctrl+shift+X – handles multiple modifiers
  • alt + shift + L – you can use whitespace inside hotkey

Definition

function useHotkeys(hotkey: string, handler: (event: KeyboardEvent) => void): void;
Build fully functional accessible web applications with ease
Feedback
Your feedback is most valuable contribution to the project, please share how you use Mantine, what features are missing and what is done good
Leave feedback