forked from stackworx/formik-mui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Select.tsx
49 lines (43 loc) · 1.24 KB
/
Select.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
import * as React from 'react';
import MuiSelect, {
SelectProps as MuiSelectProps,
} from '@material-ui/core/Select';
import { FieldProps } from 'formik';
export interface SelectProps
extends FieldProps,
Omit<MuiSelectProps, 'value'> {}
export const fieldToSelect = ({
field,
form: { isSubmitting, setFieldValue },
disabled,
...props
}: SelectProps): MuiSelectProps => {
const onChange = React.useCallback(
(event: React.ChangeEvent<{ value: unknown }>) => {
// Special case for multiple and native
if (props.multiple && props.native) {
const { options } = event.target as HTMLSelectElement;
const value: string[] = [];
for (let i = 0, l = options.length; i < l; i += 1) {
if (options[i].selected) {
value.push(options[i].value);
}
}
setFieldValue(field.name, value);
} else {
field.onChange(event);
}
},
[field.name, props.multiple, props.native]
);
return {
disabled: disabled ?? isSubmitting,
...props,
...field,
onChange,
};
};
export const Select: React.ComponentType<SelectProps> = (
props: SelectProps
) => <MuiSelect {...fieldToSelect(props)} />;
Select.displayName = 'FormikMaterialUISelect';