useShortcut

Free · MIT

True on Apple platforms, where "mod" is ⌘ rather than Ctrl.

Markdown

Preview

Install

With the Candor CLI

First time? Get started sets up the registry and theme. Or with shadcn directly: npx shadcn@latest add @candor/use-shortcut

Usage

TSX · The example above
"use client"

import * as React from "react"
import { comboKeys, useShortcut } from "@/lib/use-shortcut"
import { Kbd, KbdGroup } from "@/components/ui/kbd"

export default function Example() {
  const [count, setCount] = React.useState(0)
  useShortcut("mod+j", () => setCount((n) => n + 1))
  return (
    <p className="flex items-center gap-2 text-sm">
      Press
      <KbdGroup>
        {comboKeys("mod+j").map((k) => (
          <Kbd key={k}>{k}</Kbd>
        ))}
      </KbdGroup>
      — pressed {count} {count === 1 ? "time" : "times"}.
    </p>
  )
}

Functions

isApple()

True on Apple platforms, where "mod" is ⌘ rather than Ctrl.

comboKeys(combo: string)

The keys of a combo as they should be printed: "mod+k" → ["⌘", "K"] on a Mac and ["Ctrl", "K"] elsewhere.

useShortcut(combo: string, handler: (e: KeyboardEvent) => void, { enabled = true }: { enabled?: boolean | undefined } = {})

Run handler when a key combo is pressed anywhere on the page: "mod+k", "mod+shift+o", "?", "escape". A combo without mod or alt is ignored while the person is typing in a field, so "?" still types a question mark.