Ant Design - filter a column by all its existed data

Viewed 5353

In Ant Design Table how could I filter a column by all its existed data ?

For example - in this table - https://codesandbox.io/s/ww1lpn4k4l there are 3 different names, and you can filter by two of them because they defined them in the filters propriety. I want to have the ability to filter by all the 3 names (or more) automatically, it's mean - without specify them.

How could I achieve that ?

2 Answers

You can define helper function which closure data, and return formatted value:

const filterData = data => formatter => data.map( item => ({
      text: formatter(item),
      value: formatter(item)
  });

And next, in your columns definition:

const columns = [{
  title: 'Name',
  dataIndex: 'name',
  filters: filterData(data)(i => i.name),
  // ...

Submenu logic is a bit more complex, however you could do something like:

const splitName = index => dataItem => dataItem.name.split(" ")[index];

const columns = [{
  title: 'Name',
  dataIndex: 'name',
  filters: [
    ...filterData(data)(splitName(0)),
    {
      text: 'Submenu',
      value: 'Submenu',
      children: filterData(data)(splitName(1))
    }
  ],

Hope it helps.

Complementing Alex's answer to avoid duplicate text and values ​​using lodash

Import lodash

import _ from "lodash";

Helper function

const filterData = data => formatter => data.map( item => ({
    text: formatter(item),
    value: formatter(item)
}));

columns definition with lodash solution

const columns = [{
  title: 'Name',
  dataIndex: 'name',
  filters: _.uniqWith(filterData(data)(i => i.name),, _.isEqual),
  // ...
Related