Created
February 6, 2016 19:58
-
-
Save Craga89/5215e0e5079741b856d8 to your computer and use it in GitHub Desktop.
A workaround for react-select 1.0.0 to implement allowCreate functionality
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let isSelected = (values, selectedValue) => { | |
if (!values || values.length < 1) { | |
return false; | |
} | |
for (let { value } of values) { | |
if (selectedValue === value) { | |
return true; | |
} | |
} | |
return false; | |
} | |
let filterOptions = (options, filter, currentValues) => { | |
let filteredOptions = options.reduce((memo, option) => { | |
// Optgroup support | |
if (!('value' in option)) { | |
memo.push(option); | |
} | |
// If a filter is present | |
else if (filter && filter.length >= 1) { | |
let valueNormalized = option.value.toLowerCase().trim(); | |
let filterNormalized = filter.toLowerCase().trim(); | |
if (valueNormalized.indexOf(filterNormalized) > -1) { | |
memo.push(option); | |
} | |
} | |
// Show everything available that's not already selected if no filter is used | |
else if (!isSelected(currentValues, option.value)) { | |
memo.push(option); | |
} | |
return memo; | |
}, | |
[]); | |
// Only display `Add ${filter}` if no other options are available | |
if (filteredOptions.length < 1 && filter) { | |
filteredOptions.push({ | |
label: `Add ${filter}`, | |
value: filter, | |
create: true | |
}); | |
} | |
return filteredOptions; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment