forked from jossmac/react-select-simple-value
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
42 lines (33 loc) · 1.06 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Utils
function flatten(arr) {
return arr.reduce((acc, val) => (Array.isArray(val.options)
? acc.concat(flatten(val.options))
: acc.concat(val)
), []);
}
const clean = x => x.trim();
const toArray = str => str.split(',').map(clean);
const toString = arr => arr.join(',');
function getValue(opts, val, getOptVal, isMulti) {
if (val === undefined) return undefined;
const options = flatten(opts);
const value = isMulti
? options.filter(o => toArray(val).includes(getOptVal(o)))
: options.find(o => getOptVal(o) === val);
return value;
}
// Component
const defaultGetOptionValue = opt => opt.value;
function ReactSelectSimpleValue({
children,
defaultValue: simpleDefault,
getOptionValue = defaultGetOptionValue,
isMulti = false,
options,
value: simpleValue,
}) {
const value = getValue(options, simpleValue, getOptionValue, isMulti);
const defaultValue = getValue(options, simpleDefault, getOptionValue, isMulti);
return children({ defaultValue, getOptionValue, isMulti, options, value });
}
export default ReactSelectSimpleValue;