Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Table: resetting filters programmatically

I'm using React-Table 6.7.6, and want to reset all filters programatically.

Right now, I've got this code:

return (
    <div>
        <ReactTable
            className="-striped -highlight"
            data={data}
            columns={columns}
            filterable={true}
            defaultFilterMethod={(filter, row, column) => {
                const id = filter.pivotId || filter.id;
                return row[id] !== undefined
                    ? String(row[id]).includes(filter.value)
                    : true;
            }}
        />
    </div>
);

Is there a way to reset the filter values without digging into the guts of this thing too much?

like image 550
Boris K Avatar asked Nov 26 '25 05:11

Boris K


2 Answers

Got it.

1) When you initiate your parent component, make it stateful and give it a 'filtered' property with an empty array, like this:

constructor() {
    super();
    this.state = {
        filtered: []
    };
}

2) When you set up your React Table component, connect its "filtered" property to state, like this:

filtered={this.state.filtered}

3) Connect filtering to state, like this:

onFilteredChange={filtered => {this.setState({ filtered });}}

4) Hook up a button or whatever you want to reset the filters, with an onClick method like this:

onClick={()=>this.setState({ filtered: [] })}>
like image 144
Boris K Avatar answered Nov 29 '25 08:11

Boris K


Works like a charm in react-table v6.11.4.

The only change I made was to use React Hooks like this:

const [filtered, setFiltered] = useState([]);

const handleFilteredChanged = (filterList) => {
  setFiltered(filterList);
};

const handleResetFilters = () => {
  setFiltered([]);
};

<ReactTable
    filtered={filtered}
    filterable
    onFilteredChange={handleFilteredChanged}
    ...

Thank you Boris for posting the answer.

like image 40
Alex Monkey Avatar answered Nov 29 '25 08:11

Alex Monkey