seanbun
seanbun

Reputation: 942

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

Upvotes: 8

Views: 4044

Answers (3)

Nguyen The Vinh
Nguyen The Vinh

Reputation: 1

if (!string) return true;

You can add this line before comment default search to handle the default list of options in the first time render the react-select.

Upvotes: 0

Laura
Laura

Reputation: 8630

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.

Upvotes: 12

Nitsew
Nitsew

Reputation: 3662

The react-select library does not support this out of the box. Your best solutions would be to either open an issue on the repo to request this functionality, or fork the repo and implement this functionality yourself.

Choosing the first option leaves you in a position of uncertainty– The feature request may never get approved and implemented or it could take several months.

The other solution leaves you in a situation where you take ownership of the codebase and any existing or future bugs that may come up.

You could also combine these two options and open a feature request on the repo and include the required code changes to support it. This might be nice as you would become a contributor to a widely used NPM package.

Either way, it looks like this is the line of code that combines the label and value that searches get queried against: https://github.com/JedWatson/react-select/blob/master/packages/react-select/src/filters.js#L14

I can't write the full implementation for you, but you would need to somehow include the group label in this string, and then figure out the UI to show the selection state for that group.

Upvotes: 2

Related Questions