gridcn2.0.0
Selection and shortcuts

Shortcut remapping

Change, add, or remove key bindings, bind your own commands, and show users a shortcuts dialog that always matches the live keymap.

The keymap prop on DataGridProvider changes the key bindings of the grid. The data-grid-keybindings add-on renders them. useDataGridKeybindings mounts a dialog that lists the effective keymap with your overrides. It leaves out actions that do nothing on this grid, such as Undo without the history add-on. The commands prop binds keys to your own functions.

Click a cell to focus the grid, then press ? (shift+/) to open the shortcuts dialog — or use the button below. Mod+S runs the custom Save row command (listed in the dialog under Editing); its result shows below.

Name
Role
Score
Silent Tiger
Viewer
4
Quick Lion
Viewer
89
Swift Wolf
Manager
80
Eager Lion
User
51
Eager Tiger
Viewer
83
Silent Wolf
User
15
pnpm dlx shadcn@latest add @gridcn/data-grid-keybindings

The dialog

useDataGridKeybindings returns { plugin, open, close }. Pass plugin in plugins. The plugin mounts the dialog and binds the openKeybindings command to ?. Call open() from your own button:

import {
  DataGridBody,
  DataGridHeader,
  DataGridProvider,
  DataGridRoot,
  defineColumns,
} from "@/components/data-grid/data-grid";
import {
  useDataGridKeybindings,
} from "@/components/data-grid-keybindings/data-grid-keybindings";

type Order = { id: string; customer: string };

const columns = defineColumns<Order>()([
  { id: "customer", header: "Customer", accessorKey: "customer", type: "text" },
] as const);

export function OrdersGrid({ orders }: { orders: Order[] }) {
  const keys = useDataGridKeybindings();

  return (
    <DataGridProvider
      data={orders}
      columns={columns}
      plugins={[keys.plugin]}
    >
      <button type="button" onClick={keys.open}>Shortcuts</button>
      <DataGridRoot>
        <DataGridHeader />
        <DataGridBody />
      </DataGridRoot>
    </DataGridProvider>
  );
}

The dialog lists the default bindings, your keymap entries, and the bindings of plugins such as find and replace. A keymap entry for the same action replaces the plugin binding. Copy, cut, and paste are native browser events, so the dialog adds them to the clipboard group. The labels.keybindings group holds the dialog text. See Labels and i18n.

The ? key is a normal keymap binding. With the grid focused and no cell editor open, it opens the dialog before type-to-edit sees it. A ? typed into a text field that a cell or header renders stays with that field. Change the key with keymap={{ openKeybindings: ["F1"] }}. Remove it with keymap={{ openKeybindings: [] }}, and ? starts an edit.

DataGridKeybindingsDialog is the same dialog as a component. Use it for a custom placement or your own trigger. It mounts inside DataGridProvider.

Binding chips

BindingChips renders one binding string as a row of keycaps, like the dialog, for example <BindingChips binding="mod+z" />.

Shortcut labels for your own UI

useShortcutLabel(binding) returns the key labels of a binding as a list. It renders word names on the server and switches to glyphs on macOS after hydration. It comes from the data-grid entry point:

"use client";

import { useShortcutLabel } from "@/components/data-grid/data-grid";

export function RedoHint() {
  return <span>{useShortcutLabel("mod+shift+z").join(" ")}</span>;
}

The labels are ["⌘", "⇧", "Z"] on macOS and ["Ctrl", "Shift", "Z"] elsewhere. ctrl always renders as Ctrl. BindingChips follows the same rule. formatShortcut(binding, isMac) returns the labels for a platform that you choose, and isMacPlatform() reports the platform check.

Remapping

The keymap prop merges over DEFAULT_KEYMAP. It replaces only the actions that you name. The prop lives on DataGridProvider and on the DataGrid wrapper:

import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";

type Task = { id: string; title: string };

const columns = defineColumns<Task>()([
  { id: "title", header: "Title", accessorKey: "title", type: "text" },
] as const);

export function Tasks({ tasks }: { tasks: Task[] }) {
  return (
    <DataGrid
      data={tasks}
      columns={columns}
      keymap={{
        // keep mod+a and add a second binding that the browsers leave free
        selectAll: ["mod+a", "F8"],
        // an empty list unbinds the action
        selectColumn: [],
      }}
    />
  );
}

A binding string is modifiers plus a key, joined with +. The modifiers are mod, ctrl, shift, and alt. mod is Cmd on macOS, iOS, and iPadOS, and Ctrl elsewhere. ctrl is the physical Ctrl key on every platform. Use it where the OS reserves Cmd, as selectColumn does with Ctrl+Space. The modifiers of the event must equal the modifiers of the binding, so the binding "a" does not match Shift+A.

The key is a letter, a digit, a function key, a named key such as ArrowUp or Enter, or a printable character. A punctuation binding without shift matches with or without Shift, so "?" and "mod+/" work on every layout. Shortcut remapping options lists the key names and the matching rules. In development, a binding with an unknown modifier or key name warns in the console.

When two actions share a key combination, the most specific binding wins. On a tie, a keymap binding beats a default binding. A keymap entry that repeats a default binding counts as the default. Development mode warns once per shared combination that includes a keymap binding.

The type-to-replace trigger (typeToReplace) has no default binding. Any unbound printable key on the active cell starts an edit seeded with the typed character. A keymap entry for typeToReplace takes the action over. ["F3"] starts a plain edit on F3 only. ["a"] seeds the edit with a. [] disables it.

Reserved chords

The OS or the browser owns some key combinations. A binding on one of them never fires, or the browser acts on the key too. Shortcut remapping options lists them.

Two default bindings meet a reserved chord. With the fill add-on mounted, fillDown (mod+d) and fillRight (mod+r) take their keys while the grid has focus, and the grid calls preventDefault on them. Without the add-on, the browser keeps the keys.

Custom commands

A commands entry runs when one of its keys fires, or when the keymap binds its name. Each entry is a GridCommand:

import {
  DataGridProvider,
  DataGridRoot,
  defineColumns,
} from "@/components/data-grid/data-grid";
import type { GridCommand } from "@/components/data-grid/data-grid";

type Order = { id: string; customer: string };

const columns = defineColumns<Order>()([
  { id: "customer", header: "Customer", accessorKey: "customer", type: "text" },
] as const);

const commands: Record<string, GridCommand<Order>> = {
  saveRow: {
    keys: ["mod+s"],
    run: (ctx) => console.log("save", ctx.row),
    when: (ctx) => ctx.cell !== null,
    label: "Save row",
    group: "editing",
  },
};

export function OrdersGrid({ orders }: { orders: Order[] }) {
  return (
    <DataGridProvider
      data={orders}
      columns={columns}
      commands={commands}
    >
      <DataGridRoot />
    </DataGridProvider>
  );
}

keys are the default keys of the command. An entry for the command name in the keymap prop replaces them, and an empty list unbinds the command. run receives a GridCommandCtx with api, cell, viewRowIndex, viewColumnIndex, row, and readOnly. The grid calls preventDefault before run, so mod+s opens no browser save dialog. When when returns false, the grid ignores the key and the browser runs its own action. Shortcut remapping options lists every field of GridCommand and GridCommandCtx.

On a hole of a scroll-mode grid, cell is a placeholder ref that api cannot resolve.

scope selects the moment of dispatch. "grid" runs while no edit session is open. "editing" runs during an edit session, also in editors without a text input, such as the select list. "always" runs in both. An "editing" command never takes over a grid binding outside an edit session.

Three more rules apply:

  • A name that shadows a built-in action wins over it. Development mode warns once. The names of the add-on actions are no built-in actions, so they do not warn.
  • A bound name with neither a built-in handler nor a commands entry does nothing. Development mode warns once.
  • A key bound to two or more actions follows the tie rules in Remapping.

The keymap type takes any name. To type your command names as GridAction values, for example for autocompletion, merge them into the GridActions interface. A merged name still runs through its commands entry:

export {};

declare module "@/components/data-grid/types" {
  interface GridActions {
    saveRow: true;
  }
}

On this page