link-stack/packages/ui/components/Select.tsx
2024-12-13 16:37:20 +01:00

65 lines
1.4 KiB
TypeScript

import { FC, useState, useEffect } from "react";
import { Select as InternalSelect, MenuItem } from "@mui/material";
export type SelectOption = {
value: string;
label: string;
};
type SelectProps = {
name: string;
label: string;
formState: Record<string, any>;
required?: boolean;
getOptions?: (formState: any) => Promise<SelectOption[]>;
updateFormState?: (field: string, value: any) => void;
};
export const Select: FC<SelectProps> = ({
name,
label,
formState,
required = false,
getOptions,
updateFormState,
}) => {
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 }}
value={formState.values[name] || ""}
onChange={(e: any) => updateFormState?.(name, e.target.value)}
sx={{
backgroundColor: "#fff",
}}
>
{options.map((option: SelectOption) => (
<MenuItem
key={option.value}
value={option.value}
// @ts-ignore
disabled={option.disabled ?? false}
>
{option.label}
</MenuItem>
))}
</InternalSelect>
);
};