Search code examples
reactjsreact-table

Set multiple filters in react-table using setFilter


Is it possible to filter for multiple values using setFilter? This filters any instance of '31' in the age column:

useEffect(() => {
  setFilter("age", "31");
});

I have tried adding an array but it doesn't work:

useEffect(() => {
  setFilter("age", ["31", "32"]);
});

Solution

  • Yes. You can pass any value including multiple values (array) into setFilter setter. As writen here:

    setFilter: Function(columnId, filterValue) => void
    filterValue: any
    

    But, we have to make sure that:

    1. The setFilter setter is retrieved from the table instance by the using of useTable and useFilter hooks:
    const {
     ...
     setFilter,
     ...
    } = useTable(
     {
       columns,
       data,
     },
     useFilter
    );
    
    1. The custom filter process the filterValue correctly so it will return the intended result:
    function multiSelectFilter(rows, columnIds, filterValue) {
      // beware of "31".includes(1) and ["31", "32"].includes(1)
      // this method will return a different value if you passed in a different value data type.
      return filterValue.length === 0
        ? rows
        : rows.filter((row) => filterValue.includes(row.original[columnIds]));
    }
    
    1. The custom filter is attached into the columns object together with its id:
    columns: [
      {
        Header: "Age",
        accessor: "age",
        id: "age",
        filter: multiSelectFilter    // <--- put it here
      },
    ]
    

    Then you can use the filter at your table as follows:

      function Table({ columns, data, filteredAges }) {
    
        const {
          ...
          setFilter,
          ...
        } = useTable(
          {
            columns,
            data,
          },
          useFilter
        );
        ...
    
        useEffect(() => {
          if (filteredAges) {
            setFilter("age", filteredAges);
          }
        }, [filteredAges, setFilter]);
    
        ...
    
        return (
          ...
        )
      }
    
    

    Here's the example:

    Edit competent-galileo-yixnic