Header filter example
Filter a column from its header with a searchable list of values and counts, and read the filter it writes.
Each header holds a filter button. The button opens a popover with a search box and the set values of the column, each with a row count. Check the values to keep and press Apply.
pnpm dlx shadcn@latest add @gridcn/data-grid-header-filter-demo
What the demo shows
renderHeaderFilteronDataGridRootrendersDataGridHeaderFilterin each header. The demo has twotextcolumns and twonumbercolumns, and all four get a button.- With a mouse, the button stays hidden until you hover or focus the header. On a touch screen, the button is always visible. While the column has a filter, the button stays visible. From the keyboard, Shift+Alt+ArrowUp opens the popover of the focused header button's column, or else the active cell's column.
- The search box narrows the list. The checkbox at its start checks or unchecks the values that match the search.
- Apply writes the filter. Clear removes every filter of the column.
Wire the filter
The header filter is one prop of DataGridRoot:
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; age: number };
const columns = defineColumns<Person>()([
{ id: "name", header: "Name", accessorKey: "name" },
{ id: "age", header: "Age", accessorKey: "age", type: "number" },
]);
const rows: Person[] = [{ id: "1", name: "Ada", age: 36 }];
export function FilteredGrid() {
return (
<DataGridProvider defaultData={rows} columns={columns}>
<DataGridRoot
className="h-60"
aria-label="People"
renderHeaderFilter={(ctx) => <DataGridHeaderFilter {...ctx} />}
>
<DataGridHeader />
<DataGridBody />
</DataGridRoot>
</DataGridProvider>
);
}The filter it writes
Apply picks the operator from the counts:
- If the user checks fewer values than they leave unchecked, Apply stores
isAnyOfwith the checked values. - Otherwise it stores
isNoneOfwith the unchecked values.
On a tie, Apply keeps the operator of the current set filter, or uses isAnyOf if there is none. The filter menu writes the same shape. Header filter lists every Apply rule.
A role column has five values: Admin, User, Editor, Viewer, and Manager. Checking Admin and Editor writes this filter, which defaultFilterState can start a grid with:
import type { FilterNode } from "@/components/data-grid/data-grid";
export const defaultFilterState: FilterNode[] = [
{ columnId: "role", operator: "isAnyOf", value: ["Admin", "Editor"] },
];Pass it as defaultFilterState to DataGridProvider or DataGrid.
Related
- Header filter: the popover, the keys, and server values
- Filtering: operators, groups, and the filter menu
- Quick search: find text across all columns