-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Input.tsx
116 lines (107 loc) · 2.82 KB
/
Input.tsx
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import React from 'react';
import { useTranslation } from 'react-i18next';
import Label from '../../Label';
import Error from '../../Error';
import FieldDescription from '../../FieldDescription';
import { OptionObject, SelectField } from '../../../../../fields/config/types';
import { Description } from '../../FieldDescription/types';
import ReactSelect from '../../../elements/ReactSelect';
import { Option } from '../../../elements/ReactSelect/types';
import { getTranslation } from '../../../../../utilities/getTranslation';
import './index.scss';
export type SelectInputProps = Omit<SelectField, 'type' | 'value' | 'options'> & {
showError?: boolean
errorMessage?: string
readOnly?: boolean
path: string
required?: boolean
value?: string | string[]
description?: Description
onChange?: (value: Option) => void
style?: React.CSSProperties
className?: string
width?: string
hasMany?: boolean
isSortable?: boolean
options?: OptionObject[]
isClearable?: boolean
}
const SelectInput: React.FC<SelectInputProps> = (props) => {
const {
showError,
errorMessage,
readOnly,
path,
label,
required,
value,
onChange,
description,
style,
className,
width,
options,
hasMany,
isSortable,
isClearable,
} = props;
const { i18n } = useTranslation();
const classes = [
'field-type',
'select',
className,
showError && 'error',
readOnly && 'read-only',
].filter(Boolean).join(' ');
let valueToRender;
if (hasMany && Array.isArray(value)) {
valueToRender = value.map((val) => {
const matchingOption = options.find((option) => option.value === val);
return {
label: getTranslation(matchingOption.label, i18n),
value: matchingOption.value,
};
});
} else if (value) {
const matchingOption = options.find((option) => option.value === value);
valueToRender = {
label: getTranslation(matchingOption.label, i18n),
value: matchingOption.value,
};
}
return (
<div
id={`field-${path.replace(/\./gi, '__')}`}
className={classes}
style={{
...style,
width,
}}
>
<Error
showError={showError}
message={errorMessage}
/>
<Label
htmlFor={`field-${path.replace(/\./gi, '__')}`}
label={label}
required={required}
/>
<ReactSelect
onChange={onChange}
value={valueToRender as Option}
showError={showError}
isDisabled={readOnly}
options={options.map((option) => ({ ...option, label: getTranslation(option.label, i18n) }))}
isMulti={hasMany}
isSortable={isSortable}
isClearable={isClearable}
/>
<FieldDescription
value={value}
description={description}
/>
</div>
);
};
export default SelectInput;