Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use react-dropzone with react-hook-form?

How to use react-dropzone with react-hook-form so that the form returns proper file - not just file name?

like image 346
Avani Bataviya Avatar asked Mar 09 '26 09:03

Avani Bataviya


1 Answers

Here is a work from a react-hook-form Github discussion:

export const DropzoneField = ({
  name,
  multiple,
  ...rest
}) => {
  const { control } = useFormContext()

  return (
    <Controller
      render={({ onChange }) => (
        <Dropzone
          multiple={multiple}
          onChange={e =>
            onChange(multiple ? e.target.files : e.target.files[0])
          }
          {...rest}
        />
      )}
      name={name}
      control={control}
      defaultValue=''
    />
  )
}

const Dropzone = ({
  multiple,
  onChange,
  ...rest
}) => {

  const {
    getRootProps,
    getInputProps,
  } = useDropzone({
    multiple,
    ...rest,
  })

  return (
    <div {...getRootProps()}>
      <input {...getInputProps({ onChange })} />
    </div>
  )
}

You should check out Controller API as it was made to make integration with external controlled input easier. There are quite a few examples therein as well.

like image 121
Bill Avatar answered Mar 11 '26 23:03

Bill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!