React Hotkeys

2.0.0 · active · verified Tue Apr 21

React Hotkeys is a declarative library for managing keyboard shortcuts and focus within React applications. The current stable version is 2.0.0, representing a complete internal rewrite that removed the dependency on Mousetrap and now directly leverages React's SyntheticEvent system. This change significantly improved integration and predictable behavior within the React ecosystem. The library offers both component-based APIs (`<HotKeys>`, `<GlobalHotKeys>`, `<IgnoreKeys>`) and Higher-Order Components (`withHotKeys`, `withIgnoreKeys`) to define and handle hotkeys. Key features include support for standard browser key names and Mousetrap-like syntax, the ability to define global or context-specific hotkeys, dynamic hotkey configuration at runtime, and tools to display available shortcuts to users. It ships with comprehensive TypeScript types and is optimized for performance in large applications, with over 2000 automated tests ensuring reliability. Release cadence tends to be active during major version development, followed by maintenance releases.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a global key map and then applying specific handlers to a nested component, `MyNode`. It showcases how to bind multiple key combinations to a single action and includes basic React functional component usage with `useCallback` for handler stability. The root `<HotKeys>` component defines the context for all children.

import { HotKeys } from "react-hotkeys";
import React, { useCallback } from 'react';

const keyMap = {
  SNAP_LEFT: "command+left",
  DELETE_NODE: ["del", "backspace"]
};

const MyNode = () => {
  const deleteNode = useCallback(() => {
    console.log('Delete node action triggered!');
    // Implement your node deletion logic here
  }, []);

  const handlers = {
    DELETE_NODE: deleteNode
  };

  return (
    <HotKeys handlers={handlers}>
      <div style={{ padding: '20px', border: '1px solid #ccc', margin: '10px' }}>
        Node contents. Press 'Del' or 'Backspace' to delete.
      </div>
    </HotKeys>
  );
};

const App = () => {
  return (
    <HotKeys keyMap={keyMap}>
      <div style={{ fontFamily: 'sans-serif' }}>
        <h1>React Hotkeys Demo</h1>
        <p>Focus this area and try hotkeys. Command+Left is global, Del/Backspace is on MyNode.</p>
        <MyNode />
        <MyNode />
        <input type="text" placeholder="Type here to test input ignore" style={{ marginTop: '20px' }} />
      </div>
    </HotKeys>
  );
};

export default App;

view raw JSON →