Sorting and filtering
Column filters (text / number / date / select / set / custom) and the global filter
Sort and filter from the column menu in the header. The kind of filter UI is set per column with column.filterType.
Demo
- Product —
textSet: a combined filter of condition AND selection (text). It combines the conditions "contains / equals / starts with / ends with / blank / not blank" with a set list - Category —
select: single selection (options are collected from rows automatically) - Status —
set: multiple selection with checkboxes (Excel style) - Qty —
numberSet: a combined filter of condition AND selection (numbers). It combines number conditions (greater than or equal to / between and so on) with a set list in one popover (for example, "of those 10 or more, exclude only 12") - Unit price —
auto: no kind is set; it's decided automatically from the column's values (all values are numbers, so it opens asnumberSet) - Registered —
dateSet: a combined filter of condition AND selection (dates). It combines date conditions (between / on or after / on or before and so on), relative presets (Today / This month / Last 30 days) and a set list as a three-level year / month / day tree
The global filter input at the top does partial matching across all columns. While filters are applied, the chip bar (showFilterChipBar) lists the conditions, and each can be removed from there. "Manage filters" in the column menu or the chip bar opens a panel for editing all filters in one list.
Column definitions
const columns: GridColumn<Row>[] = [
{ key: 'name', title: 'Product', width: 180, filterType: 'textSet' },
{ key: 'category', title: 'Category', width: 130, filterType: 'select' },
{ key: 'status', title: 'Status', width: 130, filterType: 'set' },
{ key: 'qty', title: 'Qty', width: 110, filterType: 'numberSet' },
{ key: 'price', title: 'Unit price', width: 130, filterType: 'auto' },
{ key: 'registered', title: 'Registered', width: 140, filterType: 'dateSet' },
]-
Options for
select/set/numberSet/textSet/dateSetare collected from rows automatically. To set them explicitly, passfilterOptions: [{ label, value }]. -
In comparisons / ranges of
number/numberSet, blank cells (null / empty string) never match (they're distinct from 0). To pick out or exclude blank rows, use the "blank / not blank" operators or the "(Blank)" item of the set list (the same rule applies todateSetdate conditions). -
In
numberSet/textSet/dateSet, applying a condition narrows the set options to only the values that satisfy it. Check states of values dropped from the options aren't discarded and come back when the condition is undone (so trying conditions is reversible). Clearing comes in three levels: "condition only", "values only" and "everything". -
The
textSetcondition (vs. the set's search box): the search box "narrows the options to choose from" and doesn't remain as a predicate. To keep "contains …" as a predicate (so matching data added later is picked up automatically), use the condition field. -
dateSet's relative presets (Today / This month / Last 30 days) are saved as relative and resolved against "today" every time the filter is evaluated (restore a state saved withgetState()the next day and the range follows). Even with the grid left open when the date changes, it switches to the next day's range automatically at midnight (if a timer was delayed by sleep and the like, at the moment the tab comes back to the foreground. It refilters only on days when the range changes, and serverSide refetches blocks; "This month" only when the month changes). To pin dates, use absolute conditions such as "Between". To hide or customize the chips, see "Configuring relative presets (dateFilterPresets)" below. -
Write your own filtering logic with
filterType: 'custom'+filterFn: (row, filterValue) => boolean. The filter screen is a single text input (the same screen as text), and the second argument offilterFnisn't the typed string itself but the descriptor{ kind: 'custom', value: 'the typed string' }.{ key: 'score', title: 'Score', width: 100, filterType: 'custom', // typing "60" keeps rows scoring 60 or more filterFn: (row, filter) => { const min = Number((filter as { value: unknown }).value); return Number.isNaN(min) || row.score >= min; } }The input's placeholder stays "Contains…", so when it means something else, explain how to use it in the column header or a tooltip.
-
Sorting is ordered by value: values that can be read as numbers → strings → blank cells (null / undefined / empty string), and blank cells go last in both ascending and descending order (as in Excel).
-
Pressing a column header while holding
Shiftadds that column to the sort (each press goes ascending → descending → removed; sorting on other columns stays). Pressing a header normally selects the column. -
Sorting / filtering / the global filter can be turned off with
enableSorting/enableColumnFilter/enableGlobalFilter(all defaulttrue).
Configuring relative presets (dateFilterPresets)
The relative preset chips of the dateSet popover can be configured per column with the column option dateFilterPresets. Unset means the three built-ins (Today / This month / Last 30 days).
// (1) Hidden (opt out): no row of chips at all
{ key: 'updatedAt', title: 'Updated', filterType: 'dateSet', dateFilterPresets: false }
// (2) Custom configuration: built-in IDs and custom definitions can be mixed (drawn in this order)
{
key: 'updatedAt',
title: 'Updated',
filterType: 'dateSet',
dateFilterPresets: [
'today', // built-in ID (default label "Today")
{
id: 'thisWeek', // this id is what's saved in the filter value (stays relative)
label: 'This week',
resolve: (now) => { // called on every filter evaluation and resolved to an absolute range
const day = now.getDay();
const monday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - ((day + 6) % 7));
return { from: monday, to: now }; // 'YYYY-MM-DD' strings or Dates (both ends inclusive)
},
},
],
}- Custom presets are "saved as relative" just like the built-ins. Only the
idis saved, andresolve(now)resolves it to an absolute range on every evaluation (re-resolving when the date changes while open works the same as the built-ins). resolvereturns{ from?, to? }(both ends inclusive). Returning only one side is evaluated as on or after / on or before, andfrom > tois swapped automatically. The check is by day (returning aDatedrops the time and compares it as that date). Time ranges such as "the last hour" can't be made; to filter by time, usefilterType: 'custom'+filterFn.- If you remove a custom ID from the column definition, saved conditions for that preset are evaluated as "no condition" (the safe behavior that avoids every row disappearing).
- With serverSide (
dataSource), custom IDs are sent as{ mode: 'preset', preset: id }too. Interpreting the id is the server's job (Server-side row model).
dateSet date input (default UI)
The date input of dateSet conditions isn't the native <input type="date"> but an in-house date field (to avoid the look and behavior differing by browser).
- Free typing — it accepts the same ways of writing as typing into the cell's date editor, such as
2026/7/1/2026-07-01/2026.7.1/2026年7月1日/ full-width digits and symbols (2026/7/1), and normalizes and commits on Enter / blur. Input it can't read keeps a red border and isn't committed (the applied condition stays). - Calendar — opened and closed with the button on the right of the field. Clicking the title drills up day → month list → year list, for quick moves to distant years. The footer has "Today" and "Clear" (and "← Back", which returns without choosing in the month and year views).
- It follows the dark theme / density tokens. No extra dependencies.
- How cell date values are read —
Dateinstances use the year, month and day in the browser's local time; strings use the leadingYYYY-MM-DD/YYYY/M/Dpart as is (trailing times / time zones aren't looked at).new Date('2026-07-01')is 0:00 UTC, so in time zones behind UTC (the US and others) the local date becomes the previous day (2026-06-30). When you receive date-only values from a server, it's safest to put them intorowsas strings without converting toDate.
Replacing the date input (renderFilterDateInput)
To use your app's UI library instead of the in-house field, replace the whole picker with the grid prop renderFilterDateInput (it applies only to the condition fields of the filter popover).
import { DatePickerInput } from '@mantine/dates';
<SpreadsheetGrid
renderFilterDateInput={({ value, onChange, ariaLabel }) => (
<DatePickerInput
aria-label={ariaLabel}
value={value || null} // value is 'YYYY-MM-DD' or ''
onChange={onChange} // string | Date | null can be passed as is (normalized inside)
valueFormat="YYYY/MM/DD"
size="xs"
clearable
popoverProps={{ withinPortal: false }} // ★ for outside clicks (below)
style={{ flex: 1, minWidth: 0 }}
/>
)}
/>- The context is
{ value, onChange, ariaLabel, slot: 'single' | 'from' | 'to', columnKey }.onChangealso acceptsDate/null(clear) / loosely written strings such as'2026/7/1', normalized to'YYYY-MM-DD'inside (values it can't read count as clearing). Changing the value deselects the preset chips. - Outside clicks: the filter popover closes on an outside pointerdown, so if the picker's calendar appears in a portal directly under body, using it closes the popover. Avoid this either by (1) disabling the portal so it draws inside the popover (Mantine's
popoverProps={{ withinPortal: false }}and the like; recommended), or (2) adding thedata-ssg-filter-keep-openattribute to the popup element. - A HeroUI example and the detailed contract are in "Replacing the date input" in GridColumn.
Deciding the kind automatically (filterType: 'auto')
When writing a kind for each column is a chore, filterType: 'auto' decides numberSet / textSet / dateSet from the column's values. It's explicit opt-in only; columns without filterType still have no filter, as before.
{ key: 'price', title: 'Unit price', width: 130, filterType: 'auto' }- It's decided only once, when the popover first opens, and then fixed for that column (if the kind changed on every edit or addition of rows, the applied filter and the UI would disagree).
- Priority: an applied filter → the previous decision → the
editortype hint ({ type: 'number' }/{ type: 'date' }) → sampling values (up to 1,000, excluding blanks). - It's strict. If all samples are dates it's
dateSet, if all are numbersnumberSet, and if even one is mixedtextSet(the safe side). - It decides by "can it be read as a number / date", not by the value's type. Even if the DB type is string,
'1234'counts as a number. However, values with leading zeros such as'0001'don't count as numbers (so item codes and postal codes aren't mistaken for numbers; the same as Excel). - With serverSide (
dataSource), nothing is guessed from values (the client doesn't hold all rows). If there is aneditortype, that decides it; otherwise it'stext(partial match). For columns using auto, we recommend settingeditor.
Filtering / sorting on hidden columns
Hiding a column (visible: false) doesn't clear the column filters / sorting on it; they keep narrowing / ordering the rows. The counts in the toolbar and "applied" in the filter management panel match the result. To clear them, remove them from the filter management panel or the sort management panel. The global search (quick filter) only covers visible columns.
Searching the screen text (globalFilterMatch)
By default the global filter searches the text of cell values. Columns whose values are codes ('kanto') and whose screen shows valueFormatter display names ("East"), and columns showing "43,340" with numberFormatter(), don't match the screen text. globalFilterMatch="display" searches only the screen text (the result of valueFormatter), and "both" searches either the value text or the screen text (since 1.1.0). Find in cells (find) always searches the screen text. For code and display name columns, see Values and labels.
<SpreadsheetGrid columns={columns} rows={rows} globalFilterMatch="both" />It's a clientSide-only setting. With serverSide (dataSource), the global filter text is just passed to the server, so the server decides whether to search display names too.
Row selection while filtered
In tables with enableRowSelection, pressing the header (top left) checkbox while filters hide rows selects only the visible rows. If all visible rows are selected, pressing again clears only the visible rows (the selection of hidden rows stays). The checkbox state (none / some / all) is also decided by visible rows only. The handle's selectAllRows() selects all rows regardless of filters.
Leaving filtering / sorting to someone else (manualFiltering / manualSorting)
In a setup where "conditions are on the server (SQL WHERE / ORDER BY) and rows are on the client (the filtered result is passed as rows)", you want the filter / sort UI as is but don't want the grid itself to filter and sort rows (it would be done twice / sorting a result cut off at a limit changes its meaning). Set manualFiltering / manualSorting (both default false) to true, and the UI and state (GridState / onStateChange) work as before while only the row processing stops.
<SpreadsheetGrid
rows={rowsFromServer}
columns={columns}
manualFiltering
// switch to server-side ORDER BY only when fetching hit the limit (no remount needed)
manualSorting={reachedLimit}
// called only when filters / sorting actually change (not for column widths and the like)
onFiltersChange={(filters) => {
// build the WHERE from filters.columnFilters (ColumnFilterValue descriptors)
}}
onSortChange={(sort) => {
// build the ORDER BY from sort
}}
/>manualFiltering: neither column filters nor the global filter are evaluated (the precomputed Float64 keys of number columns aren't built either). Whenrowsis empty while filters are on, the empty display isnoMatchingRowsText.manualSorting: sorting isn't applied. Switching back tofalseapplies client sorting right away. While sorting is manual, the table counts as "not sorted", so thelabelRow.sortModelinkage and disabling of row drag don't happen.- With serverSide (
dataSource), the grid never filters / sorts anyway, so both are ignored. - For the shape of the descriptors (the shape of each
kindofColumnFilterValue), see "Wire format of column filters" in serverSide. The same descriptors appear inGridState.filters.columnFilterson clientSide too. - The old workaround (adding
filterFn: () => trueto every column andenableGlobalFilter={false}) is no longer needed.
Supplying options asynchronously (getFilterOptions)
Options for set / select / combined (numberSet / textSet / dateSet) are collected from rows by default, but rows already filtered on the DB side only contain the chosen values. With getFilterOptions (a grid prop), a callback fetches the options every time the popover opens (a DB SELECT DISTINCT and the like).
<SpreadsheetGrid
rows={rowsFromServer}
columns={columns}
getFilterOptions={async ({ columnKey, columnFilters, signal }) => {
// columnFilters are the active filters of the other columns, excluding the open one (options narrowed by other columns' conditions, as in Excel)
const values = await db.distinct(columnKey, buildWhere(columnFilters), { limit: LIMIT + 1, signal })
return {
options: values.slice(0, LIMIT).map((v) => ({ label: v ?? '(Blank)', value: v ?? '' })),
truncated: values.length > LIMIT,
}
}}
/>- The argument is
{ columnKey, column, columnFilters, globalText, signal }. Closing / switching columns abortssignal(rejections caused by the abort don't show an error). - The return value is
{ options: { label, value }[], truncated?: boolean }.valueis the string that goes into the descriptor'svaluesas is. Pass''for blank (NULL), and'YYYY-MM-DD'for dateSet columns. - The popover shows loading / failure (with a "Retry" button) / truncation (a note with
truncated: truethat only the first part is shown). In combined columns, the condition fields stay usable while loading. - The priority is
column.filterOptions(static) >getFilterOptions> collecting from rows. The callback isn't called for columns with static options. - Columns with asynchronous options can be inverted (exclude). "Everything except" becomes
NOT INin SQL, so values outside the truncated options are handled correctly too. - The library keeps no cache. To avoid refetching with the same arguments, keep Promises in your app keyed by
columnKey+ the other columns' filters. - The search box only searches the options already fetched (it doesn't refetch with the search text sent to the server).
- The same prop works with serverSide (
dataSource) too (instead of the "no options" display).
Handling state from outside
Sort / filter state can be saved and restored with getState() / applyState() (the imperative handle), and changes come through onStateChange. To decide the initial state from URL queries or saved values, pass it to the initialState prop. applyState changes only what you pass, so you can change only the sort, as in applyState({ sort: [{ columnKey: 'qty', direction: 'desc' }] }). To follow only filters / sorting, use onFiltersChange / onSortChange (called only when that slice actually changes).
The steps for saving and restoring (including column widths and order, restoring from the URL, old saved values after changing columns) are in Saving and restoring state.