Identifying and Clearing Applied FlexGrid Filters in React
Background
In some React applications, you may need to display how many filters are currently applied to a Wijmo FlexGrid, show which columns are filtered, and allow users to clear filtering or sorting from a specific column.
You can get the active filter information from the filterDefinition property of FlexGridFilter. This property is stored as a JSON string, so it should be parsed with JSON.parse. Sorting information is available through the grid’s collectionView.sortDescriptions collection.
Steps to Complete
- Install and import the Wijmo React grid packages.
- Create the FlexGrid data and column definitions.
- Read active filters from
filterDefinition. - Track the filtered and sorted columns.
- Clear a specific column’s filter and sort.
- Clear all filters and sorting.
- Render the FlexGrid and status controls.
Getting Started
Install and import the Wijmo React grid packages
npm install @mescius/wijmo @mescius/wijmo.react.grid @mescius/wijmo.react.grid.filter @mescius/wijmo.styles
import React, { useCallback, useMemo, useRef, useState } from 'react';
import '@mescius/wijmo.styles/wijmo.css';
import { FlexGrid, FlexGridColumn } from '@mescius/wijmo.react.grid';
import { FlexGridFilter } from '@mescius/wijmo.react.grid.filter';
- The React grid package provides the
FlexGridcomponent, while the grid filter package providesFlexGridFilter.
Create the FlexGrid data and column definitions
const columns = [
{ binding: 'id', header: 'Id' },
{ binding: 'country', header: 'Country' },
{ binding: 'date', header: 'Date' },
{ binding: 'amount', header: 'Amount' },
{ binding: 'active', header: 'Active' }
];
function getData(count) {
const countries = 'US,Germany,UK,Japan,Italy,Greece'.split(',');
return Array.from({ length: count }, (_, index) => ({
id: index,
country: countries[index % countries.length],
date: new Date(2026, index % 12, (index % 28) + 1),
amount: Math.round(Math.random() * 10000),
active: index % 4 === 0
}));
}
- The
bindingvalues are important because bothfilterDefinitionandsortDescriptionsidentify columns by binding.
Read active filters from filterDefinition
function asArray(collection) {
const result = [];
for (let i = 0; i < collection.length; i++) {
result.push(collection[i]);
}
return result;
}
function getFilterDefinition(filter) {
if (!filter?.filterDefinition) {
return { defaultFilterType: filter?.defaultFilterType, filters: [] };
}
return JSON.parse(filter.filterDefinition);
}
filterDefinitioncontains the active column filters as a JSON string. Thefiltersarray contains one item for each filtered column.
Track the filtered and sorted columns
export default function App() {
const data = useMemo(() => getData(20), []);
const gridRef = useRef(null);
const filterRef = useRef(null);
const [gridState, setGridState] = useState({
filters: [],
sorts: []
});
const refreshGridState = useCallback(() => {
const grid = gridRef.current?.control;
const filter = filterRef.current;
if (!grid || !filter) {
return;
}
const filterDefinition = getFilterDefinition(filter);
const filters = (filterDefinition.filters || []).map(item => {
const column = grid.getColumn(item.binding);
return column?.header || item.binding;
});
const sorts = asArray(grid.collectionView.sortDescriptions).map(desc => {
const column = grid.getColumn(desc.property);
const columnName = column?.header || desc.property;
return `${columnName} (${desc.ascending ? 'ascending' : 'descending'})`;
});
setGridState({ filters, sorts });
}, []);
- The filter list comes from
filterDefinition.filters. The sort list comes fromcollectionView.sortDescriptions.
Clear a specific column’s filter and sort
const clearColumnFilterAndSort = useCallback((binding) => {
const grid = gridRef.current?.control;
const filter = filterRef.current;
if (!grid || !filter) {
return;
}
const filterDefinition = getFilterDefinition(filter);
filterDefinition.filters = (filterDefinition.filters || []).filter(
item => item.binding !== binding
);
filter.filterDefinition = JSON.stringify(filterDefinition);
const sortDescriptions = grid.collectionView.sortDescriptions;
for (let i = sortDescriptions.length - 1; i >= 0; i--) {
if (sortDescriptions[i].property === binding) {
sortDescriptions.splice(i, 1);
}
}
refreshGridState();
}, [refreshGridState]);
- This removes the selected column from the filter definition and removes any sort description that uses the same binding.
Clear all filters and sorting
const clearAllFiltersAndSorts = useCallback(() => {
const grid = gridRef.current?.control;
const filter = filterRef.current;
if (!grid || !filter) {
return;
}
grid.collectionView.sortDescriptions.clear();
filter.clear();
refreshGridState();
}, [refreshGridState]);
- The
clearmethod removes all filters fromFlexGridFilter, andsortDescriptions.clear()removes all sorting from the grid’sCollectionView.
Render the FlexGrid and status controls
return (
<div>
<p>
Filters ({gridState.filters.length}): {gridState.filters.join(', ') || 'None'}
</p>
<p>
Sorts ({gridState.sorts.length}): {gridState.sorts.join(', ') || 'None'}
</p>
{columns.map(column => (
<button
key={column.binding}
onClick={() => clearColumnFilterAndSort(column.binding)}
>
Clear {column.header}
</button>
))}
<button onClick={clearAllFiltersAndSorts}>
Clear All Filters and Sorting
</button>
<FlexGrid
ref={gridRef}
itemsSource={data}
allowSorting="MultiColumn"
sortedColumn={refreshGridState}
>
{columns.map(column => (
<FlexGridColumn
key={column.binding}
binding={column.binding}
header={column.header}
/>
))}
<FlexGridFilter
initialized={filter => {
filterRef.current = filter;
refreshGridState();
}}
filterApplied={refreshGridState}
/>
</FlexGrid>
</div>
);
}
- The
filterAppliedevent updates the displayed filter count after a filter is applied. ThesortedColumnevent updates the displayed sorting information after the user sorts a column.
With this setup, the React application can show the number of active filters, display the column names for active filters and sorts, clear a specific column’s filter and sort, or clear all filters and sorting from the grid.
Happy coding!