gridcn2.0.0
Sort, filter, and search

Header filter

Put a set filter button in each column header, so users check the values to keep, with counts, a search box, and optional server values.

A column header can hold its own filter button. The button opens a popover with a searchable list of the column's values. Users check the values to keep. DataGridHeaderFilter is that button. Pass it to the renderHeaderFilter slot of DataGridRoot, as renderHeaderFilter={DataGridHeaderFilter} or as a function that returns it.

Name
Role
Age
Score
Silent Tiger
Viewer
63
4
Quick Lion
Viewer
67
89
Swift Wolf
Manager
40
80
Eager Lion
User
50
51
Eager Tiger
Viewer
45
83
Silent Wolf
User
24
15
Swift Lion
Viewer
34
62
Eager Lion
Manager
21
42
Eager Eagle
Editor
25
35
Bold Tiger
Editor
19
52
Bold Bear
User
42
28
Swift Wolf
Manager
47
9
Swift Bear
Viewer
41
45
Eager Wolf
Editor
35
44
Swift Eagle
Viewer
65
51
Quick Lion
Manager
22
28
Bold Wolf
Editor
30
76
Swift Eagle
Admin
19
26
Eager Eagle
Manager
35
70
Eager Bear
Editor
33
67
Silent Lion
Manager
48
89
Silent Tiger
Manager
62
40
Eager Tiger
Manager
51
82
Silent Lion
Admin
26
16
Bold Eagle
Admin
26
38
Bold Lion
Viewer
49
3
Quick Tiger
Viewer
26
41
Bold Eagle
Editor
50
10
Swift Tiger
Editor
55
6
Silent Lion
Viewer
35
42

The header filter ships in the toolbar add-on. See Toolbar for the install command.

Header filter button

The slot passes { column, index }. Spread it into the component:

"use client";

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

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

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

export function PeopleGrid({ rows }: { rows: Person[] }) {
  return (
    <DataGridProvider defaultData={rows} columns={columns}>
      <DataGridRoot
        className="h-96"
        renderHeaderFilter={(ctx) => <DataGridHeaderFilter {...ctx} />}
      >
        <DataGridHeader />
        <DataGridBody />
      </DataGridRoot>
    </DataGridProvider>
  );
}

The button shows on each column that offers isAnyOf or isNoneOf and is not filterable: false. By default these are the text, number, date, and select columns, and columns without a type. The button stays hidden until hover or focus on a pointer device. While the column has a filter, the button stays visible and the header cell carries data-filtered.

PropTypeDefaultDescription
columnAnyColumnDefrequiredThe column that the button filters.
indexnumberrequiredThe index of the column in the header.
classNamestringnoneMerged into the classes of the filter button.
setFilterOperator"auto" | "isAnyOf" | "isNoneOf""auto"Operator of the set entry the popover writes. "auto" writes the shorter of the checked and unchecked lists. The other two always write that operator when the column allows it.

The popover

  • The list holds one entry per distinct value, with the number of rows that have it. Values that differ only in case merge into one entry, unless the column sets filter.matchCase. Apply writes the first spelling it meets. An empty value shows as "(Blanks)".
  • The popover opens with focus in the search box, which narrows the list.
  • "Select all" is a checkbox at the start of the search field. It checks or unchecks the values that match the typed text. The box is empty when none of those values is checked, indeterminate when some are, and checked when all are.
  • "Select all" comes before the search input in the Tab order, and Space toggles it.
  • The status line reads "N of M selected" for the values the search shows. Set the text with labels.toolbar.headerFilterSelectedCount.
  • The counts include only the rows that pass every other top-level filter. The column's own top-level set filter never hides its own values. A set filter of the column inside a group counts like any other filter.
  • Under filterJoin="or", the list shows every value of the column, because each filter entry can only add rows. fetchFilterValues receives an empty filters list.
  • Clear removes every filter of the column at every level, and removes the groups this leaves empty. Escape or a press outside the popover discards the selection.
  • The list reads at most 100,000 distinct values. Past that limit it shows the first values and a message.

Apply

Apply writes the set filter of the column from the checks:

The user checksApply writes
Fewer values than the unchecked onesisAnyOf with the checked values
More values than the unchecked onesisNoneOf with the unchecked values
As many as the unchecked onesThe operator of the current set filter of the column, or isAnyOf if there is none
Every listed valueNo set filter. Values outside the list stay filtered. An isAnyOf filter keeps the listed values and its outside values. An isNoneOf filter keeps its outside values.

Apply keeps every other filter, including condition filters on the same column. It reads and writes only the top-level set filter of the column. Set filters inside a group belong to the filter menu, and a line under the list tells the user that the column has some.

Apply stays off while the user checks no value, except on a server list that holds an isNoneOf entry. There, no checked value writes isNoneOf with every listed value. If the stored list needs more than 1,000 entries, Apply also stays off, and a message explains why.

The filter works in a read-only grid, because filtering writes no data.

KeyAction
Shift+Alt+ArrowUpOpens the popover of the focused header button's column, or else the active cell's column. Focus returns to the header button or the grid when the popover closes, unless you moved it elsewhere.
ArrowUp / ArrowDown / Home / End in the listMoves between values.
Space in the listChecks or unchecks the value.
Enter in the list or the search boxApplies the selection.

To change the first key, bind openColumnFilter in the grid's keymap. The filter menu uses the same list for isAnyOf and isNoneOf on a column without choices.

Server values

Pass fetchFilterValues to DataGridProvider to fill the list from your server. The popover calls it when it opens and once for each search, after inputDebounceMs (default 200 ms) without typing. The isAnyOf input of the filter menu calls it the same way. This function reads the values from an API:

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

export const fetchFilterValues: FetchFilterValues = async (ctx) => {
  const { columnId, query, signal } = ctx;
  const url = `/api/values/${columnId}?q=${encodeURIComponent(query)}`;
  const response = await fetch(url, { signal });
  return { values: await response.json() };
};

Pass it as fetchFilterValues={fetchFilterValues} to DataGridProvider. The function receives { columnId, query, filters, signal }. It returns { values: { value: string; label?: string; count?: number }[] }.

Each value has a value and an optional label. The filter stores value, so filterState, the URL, and the spec your server receives hold the code. The list shows label, and shows value when label is absent. Return { value: "DE", label: "Germany" } for a column of country codes. A count shows the number of rows beside the value. A count that is not a non-negative integer shows no number.

FieldMeaning
columnIdThe column of the popover.
queryThe text of the search box. The grid does not filter the answer with it. Treat it as untrusted input.
filtersEvery filter except the top-level set filter of this column. Use it to count values over the other filters, or ignore it.
signalAborts when the search changes, the popover closes, or the grid unmounts.

The popover shows one loading line on the first request. A new search keeps the previous list until the answer arrives. A rejected request, or an answer without a values array, shows one error line, and the next open asks again. Set the texts with labels.toolbar.headerFilterLoading and labels.toolbar.headerFilterError.

A column with options.choices keeps its declared list and never calls the function. The grid reads at most 1,000 values from an answer, cuts each text at 1,000 characters, and renders it as text. Values that differ only in letter case count as one value, and the first one stays, unless the column sets filter.matchCase. A list from the server stores the checked value entries with isAnyOf. If the column already holds one isNoneOf entry, the list stores the unchecked values with isNoneOf. Checked values stay checked when a search hides them. A filter row of a column with filter.matchCase carries matchCase: true, so your server compares with letter case.

Server mode

Without fetchFilterValues, the list shows the values of the loaded rows. The popover then shows the hint "From loaded rows" if sortMode or filterMode is "server", or if the data holds unloaded rows. A value that exists only on the server is missing from the list. Set the text with labels.toolbar.headerFilterLoadedRowsOnly.

The request is fetchFilterValues. The answer is the set values. The filter itself reaches your server through onFilterChange and request.spec.filters. See Filtering.

On this page