reactjsreact-selectreact-table-v6

Problems with filtering react-table-v6 with react-select


So I must use react table v6. Under the table I use react-select. But when I am trying filtering data in the table something going wrong. It just does not work. l will show you example of request witch I am using. And how I am trying filter data in a table.

Here is my react-select where I providing options and chanhleChange fn:

<Select
    onChange={handleChange}
    isMulti
    options={options}
/>

Here is handleChange fn:

const handleChange = v => {
  setSelectedOptions(v);
  console.log('handleChange value :', v);
};

For providing options in select with react-select library you need that trick (why so hard i dunno...).

const options = tags.map((i) => ({
  value: i,
  label: i,
}));

Here I flatten local state selectedOption, coz I want to use it as value in "includes" method

const flatenSelectedOption = selectedOption?.map(item => item?.value).flat();

After selection in the select, the data looks like, that why I flat them using flatenSelectedOption :

choosenOptionsFromselect: [
  0: {value: 'Country', label: 'Country'}
  1: {value: 'Carrier', label: 'Carrier'}
]

flatenSelectedOption : (2) ['Country', 'Carrier']

Then here I trying filter table depent on values in select.

const sortedTableByTags = tableData.filter((item) =>item.tags?.name?.includes(flatenSelectedOption));

Then here is simple rule. I we chosen some value from select we should use filtered array, if not show all data.

<ReactTable
     data={(selectedOption?.length === 0 || selectedOption == null) ? tableData : sortedTableByTags}

But sorting does not happen, when I select something from the select, I get an empty table Below if you follow the link you can see a small gif and a screenshot of the console console.log screenshot

Gif - Select work


Solution

  • So guys I solve my own problem with sorting. It helped me sort data in a table.

    const sortedTableByTags = useMemo(() => tableData.filter((item) => item?.tags?.filter(i => i?.name?.includes(selectedOption))), [tableData, selectedOption]);
    

    Second improvement which I did i was changing onChange select function to.

    const handleSelectChange = v => {
        const res = v?.map(item => item.label);
        setSelectedOptions(res);
    };