Data grid - Filtering
Easily filter your rows based on one or several criteria.
The filters can be modified through the grid interface in several ways:
- By opening the column menu and clicking the Filter menu item.
- By clicking the Filters button in the grid toolbar (if enabled).
Each column type has its own filter operators. The demo below lets you explore all the operators for each built-in column type.
See the dedicated section to learn how to create your own custom filter operator.
Single and multi-filtering
Multi-filtering
The following demo lets you filter the rows according to several criteria at the same time.
Pass filters to the grid
Structure of the model
The full typing details can be found on the GridFilterModel API page.
The filter model is composed of a list of items
and a linkOperator
:
The items
A filter item represents a filtering rule and is composed of several elements:
filterItem.columnField
: the field on which we want to apply the rule.filterItem.value
: the value to look for.filterItem.operatorValue
: name of the operator method to use (e.g. contains), matches thevalue
key of the operator object.filterItem.id
(): only useful when multiple filters are used.
The linkOperator
The linkOperator
tells the grid if a row should satisfy all (AND
) filter items or at least one (OR
) in order to be considered valid.
// Example 1: get rows with rating > 4 OR isAdmin = true
const filterModel: GridFilterModel = {
items: [
{ id: 1, columnField: 'rating', operatorValue: '>', value: '4' },
{ id: 2, columnField: 'isAdmin', operatorValue: 'is', value: 'true' },
],
linkOperator: GridLinkOperator.Or,
};
// Example 2: get rows with rating > 4 AND isAdmin = true
const filterModel: GridFilterModel = {
items: [
{ id: 1, columnField: 'rating', operatorValue: '>', value: '4' },
{ id: 2, columnField: 'isAdmin', operatorValue: 'is', value: 'true' },
],
linkOperator: GridLinkOperator.And,
};
If no linkOperator
is provided, the grid will use GridLinkOperator.Or
by default.
Initialize the filters
To initialize the filters without controlling them, provide the model to the initialState
prop.
<DataGrid
initialState={{
filter: {
filterModel: {
items: [{ columnField: 'rating', operatorValue: '>', value: '2.5' }],
},
},
}}
/>
Controlled filters
Use the filterModel
prop to control the filter applied on the rows.
You can use the onFilterModelChange
prop to listen to changes to the filters and update the prop accordingly.
<DataGrid
filterModel={{
items: [{ columnField: 'rating', operatorValue: '>', value: '2.5' }],
}}
/>
Disable the filters
For all columns
Filters are enabled by default, but you can easily disable this feature by setting the disableColumnFilter
prop.
<DataGrid disableColumnFilter />
For some columns
To disable the filter of a single column, set the filterable
property in GridColDef
to false
.
In the example below, the rating column can not be filtered.
<DataGrid columns={[...columns, { field: 'rating', filterable: false }]} />
Customize the operators
The full typing details can be found on the GridFilterOperator API page.
An operator determines if a cell value should be considered as a valid filtered value.
The candidate value used by the operator is the one corresponding to the field
attribute or the value returned by the valueGetter
of the GridColDef
.
Each column type comes with a default array of operators. You can get them by importing the following functions:
Column type | Function |
---|---|
string |
getGridStringOperators() |
number |
getGridNumericOperators() |
boolean |
getGridBooleanOperators() |
date |
getGridDateOperators() |
dateTime |
getGridDateOperators(true) |
singleSelect |
getGridSingleSelectOperators() |
You can find more information about the supported column types in the columns section.
Create a custom operator
If the built-in filter operators are not enough, creating a custom operator is an option.
A custom operator is defined by creating a GridFilterOperator
object.
This object has to be added to the filterOperators
attribute of the GridColDef
.
The main part of an operator is the getApplyFilterFn
function.
When applying the filters, the grid will call this function with the filter item and the column on which the item must be applied.
This function must return another function that takes the cell value as an input and return true
if it satisfies the operator condition.
const operator: GridFilterOperator = {
label: 'From',
value: 'from',
getApplyFilterFn: (filterItem: GridFilterItem, column: GridColDef) => {
if (!filterItem.columnField || !filterItem.value || !filterItem.operatorValue) {
return null;
}
return (params: GridCellParams): boolean => {
return Number(params.value) >= Number(filterItem.value);
};
},
InputComponent: RatingInputValue,
InputComponentProps: { type: 'number' },
};
In the demo below, you can see how to create a completely new operator for the Rating column.
Wrap built-in operators
You can create custom operators that re-use the logic of the built-in ones.
In the demo below, the selected rows are always visible even when they don't match the filtering rules.
Multiple values operator
You can create a custom operator which accepts multiple values. To do this, provide an array of values to the value
property of the filterItem
.
The valueParser
of the GridColDef
will be applied to each item of the array.
The filtering function getApplyFilterFn
must be adapted to handle filterItem.value
as an array.
Below is an example for a "between" operator, applied on the "Quantity" column.
{
label: 'Between',
value: 'between',
getApplyFilterFn: (filterItem: GridFilterItem) => {
if (!Array.isArray(filterItem.value) || filterItem.value.length !== 2) {
return null;
}
if (filterItem.value[0] == null || filterItem.value[1] == null) {
return null;
}
return ({ value }): boolean => {
return value != null && filterItem.value[0] <= value && value <= filterItem.value[1];
};
},
InputComponent: InputNumberInterval,
}
Remove an operator
To remove built-in operators, import the method to generate them and filter the output to fit your needs.
// Only keep '>' and '<' default operators
const filterOperators = getGridNumericOperators().filter(
(operator) => operator.value === '>' || operator.value === '<',
);
In the demo below, the rating
column only has the <
and >
operators.
Custom input component
The value used by the operator to look for has to be entered by the user. On most column types, a text field is used. However, a custom component can be rendered instead.
In the demo below, the rating
column reuses the numeric operators but the rating component is used to enter the value of the filter.
Custom column types
When defining a custom column type, by default the grid will reuse the operators from the type that was extended. The filter operators can then be edited just like on a regular column.
const ratingColumnType: GridColTypeDef = {
extendType: 'number',
filterOperators: getGridNumericOperators().filter(
(operator) => operator.value === '>' || operator.value === '<',
),
};
Custom filter panel
You can customize the rendering of the filter panel as shown in the component section of the documentation.
Customize the filter panel content
The customization of the filter panel content can be performed by passing props to the default <GridFilterPanel />
component.
The available props allow overriding:
- The
linkOperators
(can containsGridLinkOperator.And
andGridLinkOperator.Or
) - The order of the column selector (can be
"asc"
or"desc"
) - Any prop of the input components
Input components can be customized by using two approaches.
You can pass a sx
prop to any input container or you can use CSS selectors on nested components of the filter panel.
More details are available in the demo.
Props | CSS class |
---|---|
deleteIconProps |
MuiDataGrid-filterFormDeleteIcon |
linkOperatorInputProps |
MuiDataGrid-filterFormLinkOperatorInput |
columnInputProps |
MuiDataGrid-filterFormColumnInput |
operatorInputProps |
MuiDataGrid-filterFormOperatorInput |
valueInputProps |
MuiDataGrid-filterFormValueInput |
The value input is a special case, because it can contain a wide variety of components (the one we provide or your custom InputComponent
).
To pass props directly to the InputComponent
and not its wrapper, you can use valueInputProps.InputComponentProps
.
Customize the filter panel position
The demo below shows how to anchor the filter panel to the toolbar button instead of the column header.
Server-side filter
Filtering can be run server-side by setting the filterMode
prop to server
, and implementing the onFilterModelChange
handler.
The example below demonstrates how to achieve server-side filtering.
Quick filter
Quick filter allows filtering rows by multiple columns with a single text input.
To enable it, you can add the <GridToolbarQuickFilter />
component to your custom toolbar or pass showQuickFilter
to the default <GridToolbar />
.
By default, the quick filter considers the input as a list of values separated by space and keeps only rows that contain all the values.
Custom filtering logic
The logic used for quick filter can be switched to filter rows that contain at least one of the values specified instead of testing if it contains all of them.
To do so, set quickFilterLogicOperator
to GridLinkOperator.Or
as follow:
initialState={{
filter: {
filterModel: {
items: [],
quickFilterLogicOperator: GridLinkOperator.Or,
},
},
}}
With the default settings, quick filter will only consider columns with types 'string'
,'number'
, and 'singleSelect'
.
- For
'string'
columns, the cell must contain the value - For
'number'
columns, the cell must equal the value - For
'singleSelect'
columns, the cell must start with the value
To modify or add the quick filter operators, add the property getApplyQuickFilterFn
to the column definition.
This function is quite similar to getApplyFilterFn
.
This function takes as an input a value of the quick filter and returns another function that takes the cell value as an input and returns true
if it satisfies the operator condition.
In the example below, a custom filter is created for the date
column to check if it contains the correct year.
getApplyQuickFilterFn: (value: string) => {
if (!value || value.length !== 4 || !/\d{4}/.test(value)) {
// If the value is not a 4 digit string, it can not be a year so applying this filter is useless
return null;
}
return (params: GridCellParams): boolean => {
return params.value.getFullYear() === Number(value);
};
};
To remove the quick filtering on a given column set getApplyQuickFilterFn: undefined
.
In the demo bellow, the column "Name" is not searchable with the quick filter, and 4 digits figures will be compared to the year of column "Created on".
Parsing values
The values used by the quick filter are obtained by splitting with space.
If you want to implement a more advanced logic, the <GridToolbarQuickFilter/>
component accepts a prop quickFilterParser
.
This function takes the string from the search text field and returns an array of values.
If you control the quickFilterValues
either by controlling filterModel
or with the initial state, the content of the input must be updated to reflect the new values.
By default, values are joint with a spaces. You can customize this behavior by providing quickFilterFormatter
.
This formatter can be seen as the inverse of the quickFilterParser
.
For example, the following parser allows to search words containing a space by using the ','
to split values.
<GridToolbarQuickFilter
quickFilterParser={(searchInput) =>
searchInput.split(',').map((value) => value.trim())
}
quickFilterFormatter={(quickFilterValues) => quickFilterValues.join(', ')}
debounceMs={200} // time before applying the new quick filter value
/>
In the following demo, the quick filter value "Saint Martin, Saint Lucia"
will return rows with country is Saint Martin or Saint Lucia.
deleteFilterItem()
Deletes a GridFilterItem.
Signature:
deleteFilterItem: (item: GridFilterItem) => void
getVisibleRowModels()
Returns a sorted Map
containing only the visible rows.
Signature:
getVisibleRowModels: () => Map<GridRowId, GridRowModel>
hideFilterPanel()
Hides the filter panel.
Signature:
hideFilterPanel: () => void
setFilterLinkOperator()
Changes the GridLinkOperator used to connect the filters.
Signature:
setFilterLinkOperator: (operator: GridLinkOperator) => void
setFilterModel()
Sets the filter model to the one given by model
.
Signature:
setFilterModel: (model: GridFilterModel, reason?: GridControlledStateReasonLookup['filter']) => void
setQuickFilterValues()
Set the quick filter values ot the one given by values
Signature:
setQuickFilterValues: (values: any[]) => void
showFilterPanel()
Shows the filter panel. If targetColumnField
is given, a filter for this field is also added.
Signature:
showFilterPanel: (targetColumnField?: string) => void
upsertFilterItem()
Updates or inserts a GridFilterItem.
Signature:
upsertFilterItem: (item: GridFilterItem) => void
upsertFilterItems()
Updates or inserts many GridFilterItem.
Signature:
upsertFilterItems: (items: GridFilterItem[]) => void
gridFilterModelSelector
Signature:
gridFilterModelSelector: (apiRef: GridApiRef) => GridFilterModel
// or
gridFilterModelSelector: (state: GridState, instanceId?: number) => GridFilterModel
Example
gridFilterModelSelector(apiRef)
// or
gridFilterModelSelector(state, apiRef.current.instanceId)
gridFilterStateSelector
Signature:
gridFilterStateSelector: (state: GridState) => GridFilterState
Example
const filterState = gridFilterStateSelector(apiRef.current.state);
gridFilteredSortedRowEntriesSelector
Signature:
gridFilteredSortedRowEntriesSelector: (apiRef: GridApiRef) => { id: GridRowId; model: GridValidRowModel }[]
// or
gridFilteredSortedRowEntriesSelector: (state: GridState, instanceId?: number) => { id: GridRowId; model: GridValidRowModel }[]
Example
gridFilteredSortedRowEntriesSelector(apiRef)
// or
gridFilteredSortedRowEntriesSelector(state, apiRef.current.instanceId)
gridFilteredSortedRowIdsSelector
Signature:
gridFilteredSortedRowIdsSelector: (apiRef: GridApiRef) => GridRowId[]
// or
gridFilteredSortedRowIdsSelector: (state: GridState, instanceId?: number) => GridRowId[]
Example
gridFilteredSortedRowIdsSelector(apiRef)
// or
gridFilteredSortedRowIdsSelector(state, apiRef.current.instanceId)
gridQuickFilterValuesSelector
Signature:
gridQuickFilterValuesSelector: (apiRef: GridApiRef) => any[] | undefined
// or
gridQuickFilterValuesSelector: (state: GridState, instanceId?: number) => any[] | undefined
Example
gridQuickFilterValuesSelector(apiRef)
// or
gridQuickFilterValuesSelector(state, apiRef.current.instanceId)
gridVisibleRowCountSelector
Signature:
gridVisibleRowCountSelector: (apiRef: GridApiRef) => number
// or
gridVisibleRowCountSelector: (state: GridState, instanceId?: number) => number
Example
gridVisibleRowCountSelector(apiRef)
// or
gridVisibleRowCountSelector(state, apiRef.current.instanceId)
gridVisibleSortedRowEntriesSelector
Signature:
gridVisibleSortedRowEntriesSelector: (apiRef: GridApiRef) => { id: GridRowId; model: GridValidRowModel }[]
// or
gridVisibleSortedRowEntriesSelector: (state: GridState, instanceId?: number) => { id: GridRowId; model: GridValidRowModel }[]
Example
gridVisibleSortedRowEntriesSelector(apiRef)
// or
gridVisibleSortedRowEntriesSelector(state, apiRef.current.instanceId)
gridVisibleSortedRowIdsSelector
Signature:
gridVisibleSortedRowIdsSelector: (apiRef: GridApiRef) => GridRowId[]
// or
gridVisibleSortedRowIdsSelector: (state: GridState, instanceId?: number) => GridRowId[]
Example
gridVisibleSortedRowIdsSelector(apiRef)
// or
gridVisibleSortedRowIdsSelector(state, apiRef.current.instanceId)
gridVisibleSortedTopLevelRowEntriesSelector
Signature:
gridVisibleSortedTopLevelRowEntriesSelector: (apiRef: GridApiRef) => { id: GridRowId; model: GridValidRowModel }[]
// or
gridVisibleSortedTopLevelRowEntriesSelector: (state: GridState, instanceId?: number) => { id: GridRowId; model: GridValidRowModel }[]
Example
gridVisibleSortedTopLevelRowEntriesSelector(apiRef)
// or
gridVisibleSortedTopLevelRowEntriesSelector(state, apiRef.current.instanceId)
gridVisibleTopLevelRowCountSelector
Signature:
gridVisibleTopLevelRowCountSelector: (apiRef: GridApiRef) => number
// or
gridVisibleTopLevelRowCountSelector: (state: GridState, instanceId?: number) => number
Example
gridVisibleTopLevelRowCountSelector(apiRef)
// or
gridVisibleTopLevelRowCountSelector(state, apiRef.current.instanceId)
More information about the selectors and how to use them on the dedicated page