Key Bindings

NPM DownloadsNPM Version

Key bindings are a way to bind keys to actions. This is useful for users who prefer to use the keyboard over the mouse. Key bindings can be used to trigger actions like opening a menu, closing a dialog, or submitting a form. Key bindings can also be used to navigate through a website or application.

Installation

npm i @hookies/key-bindings

Usage

useShortcut

The useShortcut hook is used to detect modifier-based keyboard shortcuts. For example, Ctrl + C, Shift + A, Meta + S. The hook takes a callback function as an argument, which is executed when the shortcut is triggered. The hook also takes an optional options object, which can be used to prevent the default browser behavior.

import React, { useState } from "react";
import { useShortcut } from "@hookies/key-bindings";

const App = () => {
  const [message, setMessage] = useState("Press Ctrl+8");

  useShortcut(["Ctrl", "8"], () => setMessage("Shortcut Triggered!"), { preventDefault: true });

  return <h1>{message}</h1>;
};

export default App;

useShortcutExtended

The useShortcutExtended hook is used to detect any keyboard shortcut. For example, A + S, A + 1 + M, X + Z. The hook takes a callback function as an argument, which is executed when the shortcut is triggered. The hook also takes an optional options object, which can be used to prevent the default browser behavior.


import { useState } from "react";
import { useShortcutExtended } from "@hookies/key-bindings";

const App = () => {
  const [message, setMessage] = useState("Press A + S");

  useShortcutExtended(["a", "s"], () => setMessage("Shortcut Triggered!"), { preventDefault: true });

  return <h1>{message}</h1>;
};

export default App;

getOS

The getOS function is used to detect the user's operating system. This can be useful for creating platform-specific key bindings.

import { getOS } from "@hookies/key-bindings";

const os = getOS(); // MacOS, Windows, Linux, Android, iOS, Unknown

Playground

// Press keys on your keyboard to see the output

  useShortcut([], func);

Built by Amaru