Untitled

mail@pastecode.io avatar
unknown
typescript
2 years ago
1.4 kB
1
Indexable
Never
import React, { FC } from 'react';
import { useField } from 'formik';
import {
  Select,
  SelectProps,
  MenuItem,
  FormControl,
  InputLabel,
  FormHelperText,
  SelectChangeEvent,
} from '@mui/material';

interface SelectFieldProps extends SelectProps {
  data: { label: string; value?: string; time?: string }[];
  label: string;
  name: string;
  iconComponent?: FC;
}

const SelectField: FC<SelectFieldProps> = ({
  id,
  name,
  label,
  iconComponent,
  fullWidth = true,
  data,
  onChange,
  ...restProps
}) => {
  const [field, meta] = useField({
    name: name ?? '',
  });
  const isError = meta.touched && Boolean(meta.error);
  const handleSelectValue = (e: SelectChangeEvent) => {
    if (onChange) {
      onChange(e, null);
    } else {
      field.onChange(e);
    }
  };
  return (
    <FormControl fullWidth={true} error={isError} sx={{ textAlign: 'left' }}>
      <InputLabel variant="standard">{label}</InputLabel>
      <Select
        {...field}
        {...restProps}
        value={field.value}
        fullWidth={true}
        error={meta.touched && Boolean(meta.error)}
        onChange={handleSelectValue}
      >
        {data.map((item, index) => (
          <MenuItem key={index} value={item?.value}>
            {item?.label}
          </MenuItem>
        ))}
      </Select>
      {isError && <FormHelperText>{meta.error}</FormHelperText>}
    </FormControl>
  );
};
export default SelectField;