Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Select - type to search - Access to filterOption resulting array

In React Select, my understanding is that I can provide the prop options to give an initial array of options to the select menu. Another prop that I am using is filterOption which I understand to be used in a map over all the initial options and called when user types to search.

My question is this: Is there a way for me to check the array of filtered options that react select is building while react select is doing the filtering?

I ask this because I have some options which have differing search key values but identical display values for business reasons. I want to be able to add a conditional statement (probably in filterOption?) that checks if the current item has the same display key as something that has already passed react select's filter.

Thanks!

like image 719
Curious student Avatar asked Aug 20 '18 21:08

Curious student


1 Answers

You can use the filterOption as you describe.

By default react-select is searching in the label (what you called the display value) but you can totally create a filter function that look into the key value and will match the option that has a key value including the inputValue and also the other options that have the same label as the options matching like the following code:

const filterOption = (option, inputValue) => {
    const { label, value } = option;
    // looking if other options with same label are matching inputValue
    const otherKey = options.filter(
      opt => opt.label === label && opt.value.includes(inputValue)
    );
    return value.includes(inputValue) || otherKey.length > 0;
  };

Here a live demo for the function below.

like image 193
Laura Avatar answered Oct 17 '22 17:10

Laura