Hook Master 🚀

useKeyBind

Listen for keys combinations on document element

Usage

useKeyBind accepts as its first argument an array of key-binds and handler tuples:

  • keybinds - keybind string, for example ctrl+E, shift+alt+L, mod+S
  • handler - event handler called when a given combination was pressed
  • options - object with extra options for keybind handler
import { useKeyBind } from 'hook-master-react';
 
function Demo() {
  // ctrl + J and ⌘ + J to toggle color scheme
  // ctrl + K and ⌘ + K to search
  useKeyBind([
    ['mod+J', () => console.log('Toggle color scheme')],
    ['ctrl+K', () => console.log('Trigger search')],
    ['alt+mod+shift+X', () => console.log('Rick roll')],
  ]);
 
  return null;
}

The second argument is a list of HTML tags on which keybinds should be ignored. By default, keybinds events are ignored if the focus is in input, textarea and select elements.

import { useKeyBind } from 'hook-master-react';
 
function Demo() {
  // Ignore keybinds events only when focus is in input and textarea elements
  useKeyBind(
    [['ctrl+K', () => console.log('Trigger search')]],
    ['INPUT', 'TEXTAREA']
  );
 
  // Empty array – do not ignore jeybinds events on any element
  useKeyBind([['ctrl+K', () => console.log('Trigger search')]], []);
}

With getKeyBindHandler you can also add events to any dom node using .addEventListener:

import { getKeyBindHandler } from 'hook-master-react';
 
document.body.addEventListener(
  'keydown',
  getKeyBindHandler([
    ['mod+Enter', () => console.log('Submit')],
    ['mod+S', () => console.log('Save')],
  ])
);

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 keybind
  • ArrowLeft – you can use special keys using this format
  • shift + [plus] – you can use [plus] to detect + key

Types

hook-master-react exports KeyBindItemOptions and KeyBindItem types:

interface KeyBindItemOptions {
  preventDefault?: boolean;
}
 
type KeyBindItem = [
  string,
  (event: KeyboardEvent) => void,
  KeyBindItemOptions?,
];

KeyBindItem type can be used to create keybind items outside of useKeyBind hook:

import { KeyBindItem, useKeyBind } from 'hook-master-react';
 
const keybinds: KeyBindItem[] = [
  [
    'mod+J',
    () => console.log('Toggle color scheme'),
    { preventDefault: false },
  ],
  ['ctrl+K', () => console.log('Trigger search')],
  ['alt+mod+shift+X', () => console.log('Rick roll')],
];
 
useKeyBind(keybinds);

Definition

function useKeyBind(
  keybinds: KeyBindItem[],
  tagsToIgnore?: string[],
  triggerOnContentEditable?: boolean
): void;

On this page