Files
HKSingleParty/03_source/frontend/src/components/hook-form/rhf-upload.tsx
louiscklaw db805f23b6 update
2025-05-28 21:06:12 +08:00

45 lines
1.3 KiB
TypeScript

import type { BoxProps } from '@mui/material/Box';
import { Controller, useFormContext } from 'react-hook-form';
import { Upload } from '../upload';
import type { UploadProps } from '../upload';
// ----------------------------------------------------------------------
export type RHFUploadProps = UploadProps & {
name: string;
slotProps?: {
wrapper?: BoxProps;
};
};
// ----------------------------------------------------------------------
export function RHFUpload({ name, multiple, helperText, ...other }: RHFUploadProps) {
const { control, setValue } = useFormContext();
return (
<Controller
name={name}
control={control}
render={({ field, fieldState: { error } }) => {
const uploadProps = {
multiple,
accept: { 'image/*': [] },
error: !!error,
helperText: error?.message ?? helperText,
};
const onDrop = (acceptedFiles: File[]) => {
const value = multiple ? [...field.value, ...acceptedFiles] : acceptedFiles[0];
setValue(name, value, { shouldValidate: true });
};
// return <>{JSON.stringify({ t: field.value })}</>;
return <Upload {...uploadProps} value={field.value} onDrop={onDrop} {...other} />;
}}
/>
);
}