/
File.js
72 lines (67 loc) 路 2.29 KB
/
File.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import React, { useMemo, useCallback, useRef } from "react";
import { useField } from "formik";
import * as MuiFileDropzone from "mui-file-dropzone";
import { InputLabel } from "@mui/material";
import HelperText from "./HelperText.js";
import PropTypes from "prop-types";
const { DropzoneArea } = MuiFileDropzone;
export default function File({ name, accept, hint, label }) {
const [, { initialValue }, { setValue }] = useField(name),
loadedRef = useRef(null);
const initialFiles = useMemo(() => {
if (!initialValue || initialValue === "__clear__") {
return [];
} else if (initialValue.type && initialValue.body) {
return [initialValue.body];
} else if (typeof initialValue === "string") {
return [initialValue];
}
}, [initialValue]),
acceptedFiles = useMemo(
() => (accept ? accept.split(",") : null),
[accept]
),
setFile = useCallback(
(files) => {
if (!loadedRef.current) {
// initialFiles loaded
loadedRef.current = files && files.length ? files[0] : true;
return;
}
if (files && files.length) {
if (files[0] !== loadedRef.current) {
const { name, type } = files[0];
setValue({
name,
type,
body: files[0],
});
}
} else if (initialValue) {
setValue("__clear__");
} else {
setValue(null);
}
},
[initialValue]
);
return (
<>
<InputLabel shrink>{label}</InputLabel>
<DropzoneArea
initialFiles={initialFiles}
acceptedFiles={acceptedFiles}
onChange={setFile}
filesLimit={1}
maxFileSize={100000000}
/>
<HelperText name={name} hint={hint} />
</>
);
}
File.propTypes = {
name: PropTypes.string,
accept: PropTypes.string,
label: PropTypes.string,
hint: PropTypes.string,
};