-->

How can i add more searchable options to React-Sel

2019-08-27 20:21发布

问题:

So what i need to do is have the search form of react-select not only react to id an value, but i also want it to be able to search for synonyms of the select options.

For example in a unit of measures list:

{
"id": "MIN",
"name": "minute",
"synonym": "time"
}

I want to be able to type in "min", "minute" or "time" and end up with the selection "minute".

I tried it with pushing another element into the array:

mapUnitOfMeasure()
{
    const results = [ ];
    for(const c of measureUnits)
        results.push({ value : c.id, label : c.name, syn: c.synonym });
    }
    return results
}

In my render method, the select element looks like this:

<Select
                className="react-select"
                placeholder=""
                disabled={this.state.disabled}
                value={this.state.value}
                onChange={this.handleChange.bind(this)}
                onBlur={this.handleBlur.bind(this)}
                searchable={true}
                clearable={true}
                multi={false}
                noResultsText={i18n.getMessage('CurrencyInput.search.form.noResults')}
                options={this.mapUnitOfMeasure()} />
        )

But "syn" never reacts to a search query.

Anyone have an idea how i can make it work?

回答1:

I suggest you to use filterOptions props that allows you to create your own filter function.

By default it works like this:

filterOptions={(options, filter, currentValues) => {
  // Do no filtering, just return all options
  return options;
}}

If you want to make a search in label and syn you can use the function like this:

filterOptions = (options, filterString, values) => {
  return options.filter(
    x => x.synonym.includes(filterString) || x.label.includes(filterString)
  );
};

WARNING

Using filterOptions will override filterOption, matchPos, matchProp, ignoreCase and ignoreAccents options. You will have to take care of those props by yourself.

Here a live example.