link-stack/packages/ui/components/Select.tsx

66 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-04-29 17:27:25 +02:00
import { FC, useState, useEffect } from "react";
import { Select as InternalSelect, MenuItem } from "@mui/material";
export type SelectOption = {
value: string;
label: string;
};
2024-04-24 21:44:05 +02:00
type SelectProps = {
name: string;
label: string;
formState: Record<string, any>;
2024-04-29 17:27:25 +02:00
required?: boolean;
getOptions?: (formState: any) => Promise<SelectOption[]>;
2024-04-30 11:39:16 +02:00
updateFormState?: (field: string, value: any) => void;
2024-04-24 21:44:05 +02:00
};
export const Select: FC<SelectProps> = ({
name,
label,
formState,
2024-04-29 17:27:25 +02:00
required = false,
getOptions,
2024-04-30 11:39:16 +02:00
updateFormState,
2024-04-29 17:27:25 +02:00
}) => {
const [options, setOptions] = useState([] as SelectOption[]);
useEffect(() => {
const fetchData = async () => {
if (getOptions) {
const opts = await getOptions(formState);
setOptions(opts);
}
};
fetchData();
}, [getOptions, formState]);
return (
<InternalSelect
fullWidth
name={name}
label={label}
variant="outlined"
required={required}
size="small"
inputProps={{ id: name }}
2024-04-30 11:39:16 +02:00
value={formState.values[name] || ""}
onChange={(e: any) => updateFormState?.(name, e.target.value)}
2024-04-29 17:27:25 +02:00
sx={{
backgroundColor: "#fff",
}}
>
{options.map((option: SelectOption) => (
2024-12-13 16:37:20 +01:00
<MenuItem
key={option.value}
value={option.value}
// @ts-ignore
disabled={option.disabled ?? false}
>
2024-04-29 17:27:25 +02:00
{option.label}
</MenuItem>
))}
</InternalSelect>
);
};