2

I'm trying to implement a custom filter using react bootstrap table 2 in a function component, but when I use the getFilter function to get access to the filter, the setFilter didn't work and filter.text stay at null

const ExempleTable = () => {
  const [filter, setFilter] = useState({ text: null });

  const columns = [{
    dataField: 'text',
    text: 'Text',
    filter: textFilter({
      getFilter: (textFilter) => setFilter({ text: textFilter }),
    })
  }];

  const setTextFilter = (e) => filter.text && filter.text(e.currentTarget.value);

  return (
    <>
      <input onChange={setTextFilter} />
      <BootstrapTable
        filter={filterFactory()}
        data={[{ text: "Je suis un test"}]}
        columns={columns}
      />
    </> 
  );
}

Here filter.text is always at null even after the setFilter. Is it possible to do it like that and to make it work ? Is there any workaround to make a programmatically filter inside a function component ?

Nicolas Menettrier
  • 1,647
  • 1
  • 13
  • 28

1 Answers1

-1

As far as I know, getFilter is intended to gain access to the filter implemented by react-bootstrap-table-2, and not to overwrite it. So, if you do something like this:

const columns = [{
    dataField: 'text',
    text: 'Text',
    filter: textFilter({
      getFilter: (textFilter) => { this.setFilter = textFilter; },
    })
  }];

Then, you can later use this setFilter function to programmatically set the column filter by invoking the function like this:

invokeFilterFunction = (e) => {
    this.setFilter(e.currentTarget.value);
}

return (
  <>
    <input onChange={invokeFilterFunction} />
    <BootstrapTable
      filter={filterFactory()}
      data={[{ text: "Je suis un test"}]}
      columns={columns}
    />
  </> 
  );

If you want to overwrite the column filter function, I think you should use onFilter instead. According to the Storybook, you can define your own filter function, like this:

  myOwnFirstFilter = (filterVal, data) => {
    if (filterVal) {
      return data.filter(text => text && text.indexOf(filterVal) !== -1);
    }
    return data;
  }

And then, set the filter in the column like this:

const columns = [{
    dataField: 'text',
    text: 'Text',
    filter: textFilter({
      onFilter: this.myOwnFirstFilter,
    })
  }];
dcontard
  • 135
  • 2
  • 7
  • Bit late but it's not what I was asking for. I did not wanted to overwrite the filter, I just wanted to use it inside function component instead of class component, that's it. I finally did my filter without using the react-bootstrap table functionnality. – Nicolas Menettrier May 25 '21 at 10:00