How to reset filter fields in React Table?

Angel Cuenca picture Angel Cuenca · Dec 5, 2017 · Viewed 9k times · Source

Is there an instruction for reset the filter fields in some moment ? To filter for any column works fine calling in onFetchData an Ajax call to get the data filtered. But some actions that I need after info filtered, re-render the table. In another function inside my class I execute:

this.setState({
   filter: []
});

But the info to filter after table is updated are still in the fields.

<ReactTable
    data={this.state.data}
    loading={this.state.loading}
    pages={this.state.pages}
    filterable
    columns={[
        {
            Header: "First Name",
            id: "firstName",
            accessor: d => d.firstName,
            Filter: ({ filter, onChange }) => (
                <input className="form-control input-sm"  onChange={event => onChange(event.target.value)} value={filter ? filter.value : ''} />
            )
        },
        {
            Header: "Last Name",
            accessor: "lastName",
            Filter: ({ filter, onChange }) => (
                <input className="form-control input-sm"  onChange={event => onChange(event.target.value)} value={filter ? filter.value : ''} />
            )
        }
    ]}
    onFilteredChange={(column, value) => {
        //Code
    }}
    onFetchData={(state, instance) => {
        //Ajax call
    }}
    defaultPageSize={10}
    className="-striped -highlight"
    manual
/>

Answer

Boris K picture Boris K · Jan 4, 2018

Check it out:

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: [] })}>

Easy, or what?