Skip to main content Skip to footer

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

  1. Install and import the Wijmo React grid packages.
  2. Create the FlexGrid data and column definitions.
  3. Read active filters from filterDefinition.
  4. Track the filtered and sorted columns.
  5. Clear a specific column’s filter and sort.
  6. Clear all filters and sorting.
  7. 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 FlexGrid component, while the grid filter package provides FlexGridFilter.

 

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 binding values are important because both filterDefinition and sortDescriptions identify 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);
}
  • filterDefinition contains the active column filters as a JSON string. The filters array 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 from collectionView.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 clear method removes all filters from FlexGridFilter, and sortDescriptions.clear() removes all sorting from the grid’s CollectionView.

 

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 filterApplied event updates the displayed filter count after a filter is applied. The sortedColumn event 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!

Andrew Peterson

Technical Engagement Engineer