I am using react-select' Creatable
to make a dropdown and allow user to create new item to the list.
This is what I have:
<Creatable
name="form-field-name"
value={this.props.selectWorker}
options={this.props.selectWorkers}
onChange={this.props.handleSelectWorker}
/>
Right now user can create new name even though it already exist, creating duplicates like shown below.
I saw that there is an option called isOptionUnique
on react-select site.
Searches for any matching option within the set of options. This function prevents duplicate options from being created. By default this is a basic, case-sensitive comparison of label and value. Expected signature: ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean
I have not been able to use it. I have tried isOptionUnique=true
, isOptionUnique={options:this.props.workers}
, but I got Creatable.js:173 Uncaught TypeError: isOptionUnique is not a function
error.
I can't find an example for isOptionUnique
, what is the best way to filter react-select to prevent duplicates using Creatable
?
It's expecting a function
isOptionUnique(prop) {
const { option, options, valueKey, labelKey } = prop;
return !options.find(opt => option[valueKey] === opt[valueKey])
}
Don't forget to add it to your component instance
isOptionUnique={this.isOptionUnique}
This can also be achieved using the isValidNewOption
prop.
isValidNewOption = (inputValue, selectValue, selectOptions) => {
if (
inputValue.trim().length === 0 ||
selectOptions.find(option => option.email === inputValue)
) {
return false;
}
return true;
}
you define a function taking three parameter of the inputValue you typed in, the selectValue if a value is selected and the existing options as selectOptions
.
The function should return true or false dependent on what conditions you want a new option to be valid. this will prevent addition of duplicates.
In the case above we prevent adding of new options if there is no text or if the email already exists in the available options
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With