Skip to content
OVEX TECH
Education & E-Learning

Easily Add Custom Hotkeys to Your Website with Tanstack

Easily Add Custom Hotkeys to Your Website with Tanstack

Learn to Implement Custom Hotkeys with the Tanstack Hotkey Library

Integrating custom keyboard shortcuts, or hotkeys, can significantly enhance user experience on your website. However, building this functionality from scratch can be complex and time-consuming. The Tanstack hotkey library simplifies this process, making it incredibly easy to add powerful hotkey features to your web applications. This guide will walk you through various examples, from basic setups to advanced features like recording and saving user-defined hotkeys.

What You’ll Learn

This tutorial will cover the following:

  • How to use the useHotkey hook for basic and advanced hotkey configurations.
  • Understanding modifier keys (mod) for cross-platform compatibility (Windows/Mac).
  • Leveraging TypeScript for type safety and autocompletion with hotkeys.
  • Configuring hotkey options such as target, enabled, conflictBehavior, and more.
  • Using useHeldKeys and useKeyHold hooks to track currently pressed keys.
  • Implementing sequential hotkeys using arrays of key combinations.
  • Building a user-configurable hotkey system with the useHotkeyRecorder hook.

Prerequisites

  • Basic understanding of React and JavaScript.
  • Familiarity with TypeScript (helpful but not strictly required for basic usage).
  • A modern web development environment set up (e.g., Create React App, Vite).

Step 1: Setting Up the Tanstack Hotkey Library

First, you need to install the library. Open your terminal in your project directory and run:

npm install @tanstack/react-hotkeys
# or
yarn add @tanstack/react-hotkeys

Step 2: Implementing Basic Hotkeys with useHotkey

The core of the library is the useHotkey hook. It takes a hotkey combination and a callback function as arguments.

Understanding Hotkey Syntax

You can define hotkeys using string combinations. For example, 'control+s' represents pressing the Control key and the ‘S’ key simultaneously.

Using the mod Modifier

To ensure your hotkeys work correctly across different operating systems, use the mod keyword. On Windows and Linux, mod translates to the Ctrl key. On macOS, it translates to the Command key.

Example:

import { useHotkey } from '@tanstack/react-hotkeys';
import React, { useState } from 'react';

function App() {
  const [log, setLog] = useState('');

  useHotkey('mod+s', () => {
    const timestamp = new Date().toLocaleTimeString();
    setLog(`Saved at ${timestamp}`);
  });

  useHotkey('mod+z', () => {
    const timestamp = new Date().toLocaleTimeString();
    setLog(`Undo at ${timestamp}`);
  });

  useHotkey('mod+shift+z', () => {
    const timestamp = new Date().toLocaleTimeString();
    setLog(`Redo at ${timestamp}`);
  });

  return (
    

Hotkey Example

Press Ctrl+S (or Cmd+S on Mac) to save.

Press Ctrl+Z (or Cmd+Z on Mac) to undo.

Press Ctrl+Shift+Z (or Cmd+Shift+Z on Mac) to redo.

Log: {log}

); } export default App;

TypeScript Safety and Autocompletion

The library provides excellent TypeScript support. You get autocompletion for valid hotkey combinations and type safety, preventing typos and ensuring correct syntax.

Formatting Hotkeys for Display

The library can format hotkeys to match the conventions of the user’s operating system using the formatHotkey function (though this is often handled implicitly by the library in UI rendering). This means mod+s will display as Ctrl + S on Windows and Command + S on Mac.

Expert Note: While the library handles platform-specific display, you can manually implement custom type safety using TypeScript’s utility types. This involves defining types for keys, modifiers, and their combinations using string literal types and template literals. This is an advanced technique for ensuring maximum type safety in your hotkey definitions.

Step 3: Advanced Hotkey Options

The useHotkey hook accepts an optional third argument: an options object. This allows for more granular control over how and when hotkeys are triggered.

target: Scoping Hotkeys

You can specify a DOM element as the target for a hotkey. The hotkey will only be active when the target element (or its descendants) has focus.

// Hotkey only works when the element with id 'my-input' is focused
useHotkey('enter', () => console.log('Enter pressed'), { target: '#my-input' });

// Global hotkey (no target specified or target is document)
useHotkey('mod+s', () => console.log('Global save'), { target: document });

enabled: Toggling Hotkeys

Use the enabled option to easily enable or disable a hotkey dynamically.

const [isEscapeEnabled, setIsEscapeEnabled] = useState(true);

useHotkey('escape', () => console.log('Escape pressed'), {
  enabled: isEscapeEnabled,
});

// Later, to disable:
// setIsEscapeEnabled(false);

conflictBehavior: Handling Duplicate Hotkeys

This option determines how the library reacts if you define multiple hotkeys for the same key combination. Options include 'allow', 'warn', 'error', and 'replace'.

eventType: Key Down vs. Key Up

By default, hotkeys trigger on 'keydown'. You can change this to 'keyup' if needed.

useHotkey('a', () => console.log('Key A released'), { eventType: 'keyup' });

ignoreInputs: Preventing Interference with Form Elements

When ignoreInputs is enabled (defaults to a smart behavior), hotkeys might be ignored when focus is within input elements (like ,

Written by

John Digweed

1,642 articles

Life-long learner.