-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathSelectField.tsx
108 lines (103 loc) · 3.13 KB
/
SelectField.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
import { FormControl, FormErrorMessage, FormLabel, chakra } from "@chakra-ui/react";
import { Select, OptionBase } from "chakra-react-select";
import { Controller } from "react-hook-form";
import { colorIsBright } from "utils/helpers";
export interface IDropdownOption extends OptionBase {
value: string;
label: string;
subTitle?: string | undefined | null;
color?: string | undefined | null;
data?: object | undefined | null;
}
export interface ISelectFieldProps {
fieldId: string;
fieldLabel: string;
options: IDropdownOption[] | { label: string; options: IDropdownOption[] }[] | undefined;
errors: object;
control: any;
placeholder: string;
isMulti?: boolean;
isRequired?: boolean;
showLabel?: boolean;
showError?: boolean;
onChangeProp?: ((event) => void) | undefined;
}
// The examples from chakra-react-select were super helpful:
// https://www.npmjs.com/package/chakra-react-select#usage-with-react-form-libraries
function SelectField({
fieldId,
fieldLabel,
placeholder,
showLabel = true,
showError = true,
options,
errors,
control,
isMulti = false,
isRequired = true,
onChangeProp = undefined,
}: ISelectFieldProps) {
return (
<FormControl isInvalid={!!errors[fieldId]} id={fieldId}>
{showLabel && (
<FormLabel htmlFor={fieldId}>
{fieldLabel}
{isRequired && <chakra.span color="red.500"> *</chakra.span>}
</FormLabel>
)}
<Controller
control={control}
name={fieldId}
render={({ field: { onChange, onBlur, value, name, ref } }) => (
<Select
name={name}
ref={ref}
onChange={
onChangeProp
? (event) => {
onChange(event);
onChangeProp(event);
}
: onChange
}
onBlur={onBlur}
value={value}
options={options}
placeholder={placeholder}
isSearchable
tagVariant="outline"
tagColorScheme="black"
isMulti={isMulti}
focusBorderColor="blue.500"
menuPortalTarget={document.body}
styles={{
menuPortal: (provided) => ({ ...provided, zIndex: 9999 }),
}}
chakraStyles={{
control: (provided) => ({
...provided,
border: "2px",
borderRadius: "0",
borderColor: "black",
}),
multiValue: (provided, state) => ({
...provided,
border: "1px",
borderColor: colorIsBright(state.data?.color ?? "#fff")
? "gray.300"
: state.data?.color,
color: colorIsBright(state.data?.color ?? "#fff") ? "black" : "white",
background: state.data?.color || "gray.100",
borderRadius: "20",
}),
}}
/>
)}
/>
{showError && (
<FormErrorMessage>{!!errors[fieldId] && errors[fieldId].message}</FormErrorMessage>
)}
</FormControl>
);
}
export default SelectField;