Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to include group label while search options in "React Select"

I have used react-select to allow users search/filter from a list of option. However, group labels are not included in the search. Just wondering if there is any way to include group label in the search.

In below screenshot, the group label "COLORECTAL" and its options were not shown when searching "COLOR".

drop down screenshot 1

drop down screenshot 2

like image 436
seanbun Avatar asked Jan 25 '23 17:01

seanbun


1 Answers

I completely agree with Nitsew.

You could try to start with a filterOption props like this:

const filterOption = ({ label, value }, string) => {
  // default search
  if (label.includes(string) || value.includes(string)) return true;

  // check if a group as the filter string as label
  const groupOptions = groupedOptions.filter(group =>
    group.label.toLocaleLowerCase().includes(string)
  );

  if (groupOptions) {
    for (const groupOption of groupOptions) {
      // Check if current option is in group
      const option = groupOption.options.find(opt => opt.value === value);
      if (option) {
        return true;
      }
    }
  }
  return false;
};

function App() {
  return (
    <div className="App">
      <Select
        defaultValue={colourOptions[1]}
        filterOption={filterOption}
        options={groupedOptions}
      />
    </div>
  );
}

Live Code SandBox example.

like image 84
Laura Avatar answered Jan 28 '23 09:01

Laura