I am trying to use react-hook-form with react dropzone to select image.
I have followed this discussion here and used the Conroller.
Here is a wrapper from input fields.
type FieldWrapperProps = {
children: React.ReactNode;
label: string;
errorMessage?: string;
className?: string;
};
export const FieldWrapper: FunctionComponent<FieldWrapperProps> = (props: FieldWrapperProps) => {
const { children, label, errorMessage, className } = props;
return (
<div className={clsx(`mt-6 flex flex-col justify-start tracking-wide align-middle`, className)}>
<label htmlFor={label} className="text-gray-light text-base font-bold mb-2">
{label}
</label>
{children}
{errorMessage && <p className="mt-2 text-sm text-red-500 ">{errorMessage}</p>}
</div>
);
};
type ImageFieldProps = {
control: any;
};
export const ImageField: FunctionComponent<ImageFieldProps> = (props: ImageFieldProps) => {
const { control } = props;
const { getRootProps, getInputProps } = useDropzone({
accept: {
'image/jpeg': [],
'image/png': [],
},
});
return (
<Controller
name="cover"
control={control}
render={({ field }) => (
<FieldWrapper label="Cover Image">
<section className="container">
<div {...getRootProps({ className: 'dropzone' })}>
<input
{...getInputProps()}
{...field}
onChange={(e) => field.onChange(e.target.value)}
/>
<p>Drag `n` drop some files here, or click to select files</p>
<em>(Only *.jpeg and *.png images will be accepted)</em>
</div>
</section>
</FieldWrapper>
)}
/>
);
};
I have used this component inside my form like so:
const {
register,
handleSubmit,
control,
formState: { errors },
} = useForm<FormData>({
mode: 'all',
resolver: yupResolver(mySchema),
});
<form onSubmit={handleSubmit(onSubmit)}>
<ImageField control={control} />
</form>
The form renders:
The field is not clickable and input field shows greyed out in the DOM.