useHotkeys

useHotkeys (단축키)

useHotkeys 훅은 키보드 단축키를 등록하고 처리해요. 두 번째 인자는 단축키를 무시할 HTML 태그 목록이에요. 기본적으로 input, textarea, select 요소에 포커스가 있으면 단축키 이벤트를 무시해요.

출처: 문서

본문

두 번째 인자는 단축키를 무시해야 할 HTML 태그 목록이에요. 기본적으로 포커스가 input, textarea, select 요소에 있으면 단축키 이벤트를 무시해요.

import { useHotkeys } from '@mantine/hooks';

function Demo() {
  // Ignore hotkey events only when focus is in input and textarea elements
  useHotkeys(
    [['ctrl+K', () => console.log('Trigger search')]],
    ['INPUT', 'TEXTAREA']
  );

  // Empty array – do not ignore hotkey events on any element
  useHotkeys([['ctrl+K', () => console.log('Trigger search')]], []);
}

요소 대상 지정 (Targeting elements)

useHotkeys 훅은 document 요소에서만 동작해요. 다른 요소를 지원하려면 직접 이벤트 리스너를 만들어야 해요. 이를 위해 @mantine/hooks 패키지는 onKeyDown과 함께 사용해야 하는 getHotkeyHandler 함수를 내보내요.

import { useState } from 'react';
import { getHotkeyHandler } from '@mantine/hooks';
import { notifications } 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 handleSubmit = () => notifications.show({ title: 'Your message', message: value });
  const handleSave = () => notifications.show({ title: 'You saved', color: 'teal', message: value });

  return (
    <TextInput
      value={value}
      onChange={(event) => setValue(event.currentTarget.value)}
      onKeyDown={getHotkeyHandler([
        ['mod+Enter', handleSubmit],
        ['mod+S', handleSave],
      ])}
    />
  );
}

getHotkeyHandler를 사용하면 .addEventListener로 어떤 DOM 노드에도 이벤트를 추가할 수 있어요.

import { getHotkeyHandler } from '@mantine/hooks';

document.body.addEventListener(
  'keydown',
  getHotkeyHandler([
    ['mod+Enter', () => console.log('Submit')],
    ['mod+S', () => console.log('Save')],
  ])
);

지원 형식 (Supported formats)

  • mod+S — macOS의 ⌘+S, Windows의 Ctrl+S를 감지해요
  • ctrl+shift+X — 여러 수정자(modifier)를 처리해요
  • alt + shift + L — 단축키 안에 공백을 사용할 수 있어요
  • ArrowLeft — 이 형식으로 특수 키를 사용할 수 있어요
  • shift + [plus] — [plus]를 사용해 + 키를 감지할 수 있어요
  • Digit1와 Hotkey1 — MDN에 정의된 물리 키 배정을 사용할 수 있어요

타입 (Types)

@mantine/hooks 패키지는 HotkeyItemOptions와 HotkeyItem 타입을 내보내요.

interface HotkeyItemOptions {
  preventDefault?: boolean;
  usePhysicalKeys?: boolean;
}

type HotkeyItem = [
  string,
  (event: KeyboardEvent) => void,
  HotkeyItemOptions?,
];

HotkeyItemOptions의 usePhysicalKeys 옵션은 물리 키 배정을 강제해요. 이는 비-QWERTY 키보드 레이아웃에서 유용해요.

HotkeyItem 타입을 사용해 useHotkeys 훅 밖에서 단축키 항목을 만들 수도 있어요.

import { HotkeyItem, useHotkeys } from '@mantine/hooks';

const hotkeys: HotkeyItem[] = [
  [
    'mod+J',
    () => console.log('Toggle color scheme'),
    { preventDefault: false },
  ],
  ['ctrl+K', () => console.log('Trigger search')],
  ['alt+mod+shift+X', () => console.log('Rick roll')],
  [
    'D',
    () => console.log('Triggers when pressing "E" on Dvorak keyboards!'),
    { usePhysicalKeys: true }
  ],
];

useHotkeys(hotkeys);

정의 (Definition)

interface HotkeyItemOptions {
  preventDefault?: boolean;
  usePhysicalKeys?: boolean;
}

type HotkeyItem = [string, (event: KeyboardEvent) => void, HotkeyItemOptions?]

function useHotkeys(
  hotkeys: HotkeyItem[],
  tagsToIgnore?: string[],
  triggerOnContentEditable?: boolean
): void;

Exported types

HotkeyItemOptions와 HotkeyItem 타입은 @mantine/hooks에서 내보내져요.

import type { HotkeyItemOptions, HotkeyItem } from '@mantine/hooks';

더 알아보기 (Learn more)