link-stack/packages/ui/components/Select.tsx
2024-04-29 17:27:25 +02:00

57 lines
1.2 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[]>;
};
export const Select: FC<SelectProps> = ({
name,
label,
formState,
required = false,
getOptions,
}) => {
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 }}
defaultValue={formState.values[name] || ""}
sx={{
backgroundColor: "#fff",
}}
>
{options.map((option: SelectOption) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</InternalSelect>
);
};