Column filter doesn't work on React table

599 Views Asked by At

I'm working on react table and with custom filter.

In my case I have filter component and react table component which are sibling component, when user select a value from dropdown in filter component and that value is of particular column which is received using useSelector(redux toolkit) in react table but filtering is not working.

Here is code block of filter component

const ColumnFilter = ({ column }) => {
  const { filterValue, setFilter } = column;
  const { filterSliceData } = useSelector(getDataSlice);

  if (filterSliceData) {
    setFilter(filterSliceData);
  }

  return (
    <></>
  );
};

I'm getting some error when I select filter from dropdown. enter image description here

And Here is the Full example that I have created in codesandbox. https://codesandbox.io/s/react-table-column-filter-component-c5wbc7

1

There are 1 best solutions below

0
toki On

Your logic in ColumnFilter.js is causing an infinite re-render loop because it keeps causing a state change that prompts a re-render of the ColumnFilter. filterSliceData is truthy, which tells it to call setFilter, which prompts a column rerender, which re-renders ColumnFilter, where filterSliceData is truthy, and so on and so forth.

What it sounds like you want is a way to change your filter value if an external component changes. The useFilter hook exposes a setFilter method you can use for this. You can then use that setFilter method to update the filter value for your desired column based on the value from useSelector, with a useEffect or similar hook. I forked your CodeSandbox as an example. The primary downside to this approach is that it's tightly links that specific global state variable with the table itself, so some additional logic might be needed to abstract that out for your desired result.