docs/pages/examples/forms.mdx
import {FormExample} from "../../components/examples";
react-dropzone does not submit files in form submissions by default. If you need this, add a hidden file input and set the files into it.
:::warning[Spreading getRootProps() onto a <button>?]
Set type="button" on it. A <button> inside a <form> defaults to type="submit", so clicking it to open the file dialog also submits (and reloads) the form, clearing its fields.
:::
function DropzoneField({required, name}) {
const hiddenInputRef = useRef(null);
const {getRootProps, getInputProps, open} = useDropzone({
onDrop: incomingFiles => {
if (hiddenInputRef.current) {
// https://stackoverflow.com/a/68182158/1068446
const dataTransfer = new DataTransfer();
incomingFiles.forEach(v => dataTransfer.items.add(v));
hiddenInputRef.current.files = dataTransfer.files;
}
}
});
return (
<div {...getRootProps({className: "dropzone"})}>
<input type="file" name={name} required={required} style={{opacity: 0}} ref={hiddenInputRef} />
<input {...getInputProps()} />
<button type="button" onClick={open}>
Open File Dialog
</button>
</div>
);
}