Sort and filter rows
Step 7 of 8
Add a toolbar with quick search, a filter menu, and a columns menu, and sort rows with a click on a header.
Before you start, finish select and paste. Then install the toolbar add-on:
pnpm dlx shadcn@latest add @gridcn/data-grid-toolbar
A toolbar sits between the provider and the scrolling box. <DataGrid> has no slot for it, so this step uses the parts that <DataGrid> renders. DataGridProvider holds the state and the props. DataGridRoot is the scrolling box. DataGridHeader draws the column headers. DataGridBody draws the rows.
Compose the grid
Replace people-grid.tsx with this file. It keeps the undo and redo of the earlier steps:
"use client";
import {
DataGridBody,
DataGridHeader,
DataGridProvider,
DataGridRoot,
} from "@/components/data-grid/data-grid";
import {
DataGridColumnsMenu,
DataGridFilterMenu,
DataGridSearch,
DataGridToolbar,
} from "@/components/data-grid-toolbar/data-grid-toolbar";
import {
useDataGridState,
} from "@/components/data-grid-history/data-grid-history";
import { columns, type Person } from "./columns";
const people: Person[] = [
{ id: "1", name: "Ada Lovelace", age: 28, active: true },
{ id: "2", name: "Grace Hopper", age: 34, active: true },
{ id: "3", name: "Margaret Hamilton", age: 31, active: false },
];
export function PeopleGrid() {
const grid = useDataGridState(people);
return (
<DataGridProvider
{...grid}
columns={columns}
headerClickBehavior="sort"
>
<DataGridToolbar>
<DataGridSearch />
<DataGridFilterMenu />
<DataGridColumnsMenu />
</DataGridToolbar>
<DataGridRoot aria-label="Players" className="h-96">
<DataGridHeader />
<DataGridBody />
</DataGridRoot>
</DataGridProvider>
);
}Try it
- Click a header. The column sorts ascending. A second click sorts descending, and a third click removes the sort. Shift+click adds a second sort column.
- Type in the search box. The grid highlights the matches and shows how many it found. Enter moves the active cell to a match, and each further Enter moves to the next. Search never hides rows.
- Open the filter menu and add a filter. Rows that do not match the filter disappear.
- Open the columns menu and clear the checkbox of a column to hide it.
With focus in the grid or its toolbar, Ctrl/Cmd+F focuses the search box and leaves the browser find bar closed.
headerClickBehavior defaults to "select", which selects the column on a header click. Set sortable: false on a column to keep a header click from sorting it.
Next: Style the grid.