-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSelectInput.tsx
59 lines (55 loc) · 2.14 KB
/
SelectInput.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
import { useMemo } from "react";
import Select from "react-select";
import { useResourceList } from "@pennlabs/rest-hooks";
import { useField, FieldArray } from "formik";
import { selectStyles } from "../ui";
interface SelectOption {
id: number;
name: string;
}
const toSelectOptions = (options) =>
options.map((obj) => ({ value: obj.name, label: obj.name }));
export const FormikSelectInput = function ({ route, fieldName }) {
const { data: rawData } = useResourceList<SelectOption>(
route,
(id) => `${route}${id}/`
);
const [field, , helper] = useField(fieldName);
const data = useMemo(() => rawData || [], [rawData]);
const options = useMemo(() => toSelectOptions(data), [data]);
return (
<FieldArray name={fieldName}>
{({ push, remove }) => {
const values = field.value || [];
return (
<Select
isMulti
styles={selectStyles}
options={options}
value={toSelectOptions(values)}
onChange={(_, action) => {
if (action.action === "select-option") {
push(
data.filter(
(obj) =>
obj.name === action.option.value
)[0]
);
} else if (action.action === "remove-value") {
remove(
values.findIndex(
(obj) =>
obj.name ===
action.removedValue.value
)
);
} else if (action.action === "clear") {
helper.setValue([]);
}
}}
/>
);
}}
</FieldArray>
);
};