Skip to content

everdimension/keyboard-shortcut-component

Repository files navigation

KeyboardShortcut Component

tests GitHub

A handy React component that listens for keyboard combinations (hotkeys) when mounted.

Getting Started

Install

npm install keyboard-shortcut-component

Usage

Render <KeyboardShortcut /> component when you want to listen to keyboard shortcuts:

import { KeyboardShortcut } from 'keyboard-shortcut-component';

export function Component() {
  const [showDialog, setShowDialog] = useState(false);
  const openDialog = () => setShowDialog(true);
  const closeDialog = () => setShowDialog(false);
  return (
    <>
      <KeyboardShortcut combination="shift+k" onKeyDown={openDialog} />
      {showDialog ? (
        <>
          <KeyboardShortcut combination="esc" onKeyDown={closeDialog} />
          <SomeDialog />
        </>
      ) : null}
    </>
  );
}

API

<KeyboardShortcut
  combination="alt+shift+space"
  onKeyDown={(event: KeyboardEvent, combination: string) => void}
  disabled={false}
/>

Props

interface Props {
  combination: string;
  onKeyDown: (event: KeyboardEvent, combination: string) => void;
  disabled?: boolean;
}

Credits

This library uses the awesome minimalistic is-hotkey package under the hood.

About

A React component that fires a callback when a hotkey combination is pressed

Resources

License

Stars

Watchers

Forks

Packages

No packages published