gridcn2.0.0
Sort, filter, and search

Find and replace

Open a panel that finds text in the grid and replaces one match or all matches as one change, with keyboard shortcuts and undo.

Users fix the same typo in many cells without editing each cell. data-grid-find-replace adds a panel with a Find field and a Replace field. useDataGridFindReplace returns the plugin that mounts the panel. The plugin binds Mod+F to open Find and Shift+Alt+Enter to open Find and Replace.

Press Shift+Alt+Enter inside the grid to open the panel.

Name
Email
Role
Age
Silent Tiger
user0@example.com
Viewer
63
Quick Lion
user1@example.com
Viewer
67
Swift Wolf
user2@example.com
Manager
40
Eager Lion
user3@example.com
User
50
Eager Tiger
user4@example.com
Viewer
45
Silent Wolf
user5@example.com
User
24
Swift Lion
user6@example.com
Viewer
34
Eager Lion
user7@example.com
Manager
21
Eager Eagle
user8@example.com
Editor
25
Bold Tiger
user9@example.com
Editor
19
Bold Bear
user10@example.com
User
42
Swift Wolf
user11@example.com
Manager
47
Swift Bear
user12@example.com
Viewer
41
Eager Wolf
user13@example.com
Editor
35
Swift Eagle
user14@example.com
Viewer
65
Quick Lion
user15@example.com
Manager
22
Bold Wolf
user16@example.com
Editor
30
Swift Eagle
user17@example.com
Admin
19
Eager Eagle
user18@example.com
Manager
35
Eager Bear
user19@example.com
Editor
33
Silent Lion
user20@example.com
Manager
48
Silent Tiger
user21@example.com
Manager
62
Eager Tiger
user22@example.com
Manager
51
Silent Lion
user23@example.com
Admin
26
Bold Eagle
user24@example.com
Admin
26
Bold Lion
user25@example.com
Viewer
49
Quick Tiger
user26@example.com
Viewer
26
Bold Eagle
user27@example.com
Editor
50
Swift Tiger
user28@example.com
Editor
55
Silent Lion
user29@example.com
Viewer
35
pnpm dlx shadcn@latest add @gridcn/data-grid-find-replace

Pass the plugin to the grid. findReplace.open() opens the panel from your own button, with the Replace field hidden, as Mod+F does. findReplace.open("replace") shows the Replace field. findReplace.close() closes it:

"use client";

import {
  DataGridBody,
  DataGridHeader,
  DataGridProvider,
  DataGridRoot,
  defineColumns,
} from "@/components/data-grid/data-grid";
import {
  useDataGridFindReplace,
} from "@/components/data-grid-find-replace/data-grid-find-replace";

type Person = { id: string; name: string };

const columns = defineColumns<Person>()([
  { id: "name", header: "Name", accessorKey: "name" },
]);

export function PeopleGrid({ rows }: { rows: Person[] }) {
  const findReplace = useDataGridFindReplace();

  return (
    <DataGridProvider
      defaultData={rows}
      columns={columns}
      plugins={[findReplace.plugin]}
    >
      <button onClick={() => findReplace.open()}>Find</button>
      <DataGridRoot className="h-96">
        <DataGridHeader />
        <DataGridBody />
      </DataGridRoot>
    </DataGridProvider>
  );
}

Find

The Find field writes the grid's quick search. The highlights, the next and previous buttons, and the cells that Replace changes are the same cells. The toolbar search shows the same text. See Quick search.

The search is a literal text match. It ignores spaces at both ends of the Find text. Two toggles inside the Find field change the match:

  • Match case matches letter case. It is off by default.
  • Whole cell matches only cells that equal the Find text. It is off by default.

Find reads each cell as its search text: the toSearchText of its cell type, else its toText. A select cell searches its label. A number cell searches its plain value rounded to decimals, not its format, so 12.5 finds a cell that shows $12.50. A date cell searches its ISO text. A custom cell type can set toSearchText.

The status line is the last row of the panel. It shows 2 of 4 cells for the current match, No results when nothing matches, and Type to search while the Find field is empty. The number gets a + when more than 1,000 cells match.

Typing

The Find field waits for the inputDebounceMs prop of the grid (default 200 ms) after the last keystroke before it searches. Enter and blur search at once. Closing the panel with anything but Escape searches the waiting text.

Replace

Replace swaps each occurrence of the Find text in the search text of the cell, then converts the result with fromText.

  • Replace changes the current match and moves to the next one. After the last match, it moves to the first. When the active cell is a match, Replace changes that cell. When the new text still matches the Find text, the active cell still moves on.
  • Replace all changes every matching cell in the view.

Each click writes one change with the source "replace". With the undo add-on mounted, one undo reverts it. Replace all leaves the selection and the active cell where they are.

Replace skips a cell when:

  • the column is read-only, as a flag or for that row,
  • the replaced text cannot become a value of the type, such as x in a number column,
  • the replaced text is longer than 100,000 characters,
  • the column's validate rejects the new value. onValidationError receives these cells with the source "replace".

The status line shows how many cells changed and how many Replace skipped. With an async validate, it shows Validating… until the batch settles.

Where Replace works

Replace covers the visible columns of the rows in the view, on every page of a paged grid. Hidden columns, filtered-out rows, pinned rows, and the unloaded rows of a scroll-mode grid never change. With scope: "selection", it covers only the selected cells.

One Replace all changes at most replaceAllLimit cells. When more cells match, the status line says so, and the next click continues. That click skips the cells the earlier one changed, even when the replacement contains the find text. A change to the find text, the replacement, or an option starts over.

The chevron button at the start of the Find row shows and hides the Replace field. Every open sets it: Mod+F, open(), and open("find") hide it, and Shift+Alt+Enter and open("replace") show it. In a readOnly grid, the Find field works, the chevron is hidden, and Replace stays disabled. While a cell editor is open, Replace does nothing.

Check a replace before it runs

processReplace runs after the panel builds the list of changes and before it writes them. It gets the plan and a signal. Return the plan to write, or false to cancel:

import {
  useDataGridFindReplace,
} from "@/components/data-grid-find-replace/data-grid-find-replace";

export function useCheckedFindReplace() {
  return useDataGridFindReplace({
    processReplace: async ({ plan, signal }) => {
      const response = await fetch("/api/check-edit", {
        method: "POST",
        body: JSON.stringify(plan.patches),
        signal,
      });
      return response.ok ? plan : false;
    },
  });
}

The hook can drop, add, or change patches. A patch holds the new value of one cell. The grid runs the column's validate on it. A string for a non-string cell goes through fromText first. An unparseable one is skipped. The panel skips a returned patch on a hidden column with the reason "hidden".

The replace is cancelled, and the status line says Replace cancelled, when:

  • the returned plan holds more than replaceAllLimit patches,
  • the hook returns false, returns something that is not a plan, or rejects,
  • a row that the plan writes changes or goes away while the hook runs,
  • the grid turns readOnly, or a cell editor opens, while the hook runs.

Keyboard

KeyWhereAction
Mod+FgridOpens the panel with the cursor in Find. The Replace field stays hidden.
Shift+Alt+EntergridOpens the panel with the cursor in Find and the Replace field shown.
EnterFindGoes to the next match.
Shift+EnterFindGoes to the previous match.
EnterReplaceReplaces the current match.
Mod+EnterReplaceReplaces all matches.
EscapepanelCloses the panel and drops find text that is still waiting.

Focus stays in the panel field while Enter, Next, or Previous moves the active cell to a match. To move focus into the grid, call api.focus() on the grid ref. When the panel opened from the grid, Escape returns focus to the header button or grid. Mod is Cmd on macOS and Ctrl elsewhere. Outside the grid, Mod+F opens the browser's find bar. To change a key, bind openFindReplace or openFind in the grid's keymap.

With DataGridSearch also on screen, Mod+F opens this panel and takes the key from the focusSearch action, which is then unbound. Bind focusSearch in keymap to reach the toolbar search with another key.

Server mode

Find and Replace work on the rows the grid holds: the loaded rows in scroll mode, and the current page in pages mode. A client grid that pages its view holds every row. Its search and "Replace all" cover every page. A jump to a match changes the page. A search that finds nothing does not mean the server result has no match.

A grid with a totalRowCount, or with a server sortMode or filterMode, shows "Searches loaded rows only" under the fields. To hide the note, set labels.findReplace.scopeLoadedRows to "".

Find over the result

Set findScope: "result" when your server narrows the rows by spec.searchText. The count line then shows the size of the result, such as "11 rows match". Next and Previous go on into unloaded rows. Scroll mode scrolls to the next block. Pages mode asks for the next page. Replace and Replace all change loaded rows only.

Replace writes through the same path as an edit. onDataChange and onSave receive each Replace as one change with the source "replace". A refused save reverts the refused cells. See Save edits.

Options

PropTypeDefaultDescription
scope"view" | "selection""view"Which cells Replace covers.
replaceAllLimitnumber10000Most cells one Replace all changes. Clamped to 1 to 100,000.
processReplace({ plan, signal }) => plan | false | PromisenoneChecks or changes the plan before it writes. false cancels.
findScope`"loaded""result"`"loaded"
classNamestringnoneClasses merged into the panel root.

planReplace

planReplace(state, find, replacement, options) is the pure function behind the buttons. It returns { patches, skipped, remaining } and writes nothing. Pass patches to actions.updateCells(patches, { source: "replace" }) to write them. Each entry of skipped has a reason: "readonly", "unparseable", "too-long", "no-occurrence", or "hidden". The panel adds "hidden" for a processReplace patch on a hidden column. Find and replacement text longer than 1,000 characters is cut.

Labels

The panel strings live under labels.findReplace. See Labels and i18n.

On this page