A React hook that registers a global keydown listener, optionally ignoring events while typing in editable elements, for reusable keyboard shortcuts.
// Source: https://github.com/fuma-nama/fumadocs | License: MIT | Copyright 2023 Fuma
// Provided via justclaw.it.com; keep this notice with the code.
import { useEffect, useEffectEvent } from 'react';
/**
* Listen to `keydown` on window, skipping keys that are already handled or composing text.
*/
export function useHotKey(
onKeyDown: (e: KeyboardEvent) => void,
{
enabled = true,
ignoreTyping = false,
}: {
enabled?: boolean;
/** ignore it while typing in an editable element (e.g. `<input />`), or when a dialog is opened */
ignoreTyping?: boolean;
} = {},
) {
const listener = useEffectEvent((e: KeyboardEvent) => {
if (e.defaultPrevented || e.isComposing || e.keyCode === 229) return;
if (ignoreTyping && isTypingTarget(e.target)) return;
onKeyDown
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search for more like it.
Get a free API key