Search code examples
javascriptreactjsmaterial-uimui-datatable

Can I store these selected filters in a variable?


Is it possible to store these selected filters in a variable and have it updated as well when the use selects another set of filters? If so, how?

enter image description here

Codesandbox: https://codesandbox.io/s/muidatatables-custom-toolbar-forked-lrbf16


Solution

  • To achieve that, you can use onFilterChange callback, like this :

    const options = {
    ...
    
        onFilterChange: (column, filterList, type) => {
                const selectedFilters = this.extractFilters(filterList);
                console.log(selectedFilters);
              }
    }
    

    This function will be called everytime filter list changes.

    Then, you declare function extractFilters which will extract all selected filters from passed filterList and it will return array object containting all selected filters :

     extractFilters = (filterList) => {
            let selectedFilters = [];
            filterList.forEach((filter) => {
              if (filter.length > 0) {
                selectedFilters.push(...filter);
              }
            });
            return selectedFilters;
          };
    

    You can store this array in state.

    Here is working example.