Debian Codegraph @

node/react-dropzone/examples/forms/README.md

raw
1 React-dropzone does not submit the files in form submissions by default.
2
3 If you need this behavior, you can add a hidden file input, and set the files into it.
4
5
6 ```jsx harmony
7 import React, {useRef} from 'react';
8 import {useDropzone} from 'react-dropzone';
9
10 function Dropzone(props) {
11 const {required, name} = props;
12
13 const hiddenInputRef = useRef(null);
14
15 const {getRootProps, getInputProps, open, acceptedFiles} = useDropzone({
16 onDrop: (incomingFiles) => {
17 if (hiddenInputRef.current) {
18 // Note the specific way we need to munge the file into the hidden input
19 // https://stackoverflow.com/a/68182158/1068446
20 const dataTransfer = new DataTransfer();
21 incomingFiles.forEach((v) => {
22 dataTransfer.items.add(v);
23 });
24 hiddenInputRef.current.files = dataTransfer.files;
25 }
26 }
27 });
28
29 const files = acceptedFiles.map(file => (
30 <li key={file.path}>
31 {file.path} - {file.size} bytes
32 </li>
33 ));
34
35 return (
36 <div className="container">
37 <div {...getRootProps({className: 'dropzone'})}>
38 {/*
39 Add a hidden file input
40 Best to use opacity 0, so that the required validation message will appear on form submission
41 */}
42 <input type ="file" name={name} required={required} style ={{opacity: 0}} ref={hiddenInputRef}/>
43 <input {...getInputProps()} />
44 <p>Drag 'n' drop some files here</p>
45 <button type="button" onClick={open}>
46 Open File Dialog
47 </button>
48 </div>
49 <aside>
50 <h4>Files</h4>
51 <ul>{files}</ul>
52 </aside>
53 </div>
54 );
55 }
56
57
58 <form onSubmit={(e) => {
59 e.preventDefault();
60
61 // Now get the form data as you regularly would
62 const formData = new FormData(e.currentTarget);
63 const file = formData.get("my-file");
64 alert(file.name);
65 }}>
66 <Dropzone name ="my-file" required/>
67 <button type="submit">Submit</button>
68 </form>
69 ```