-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
41 lines (35 loc) · 962 Bytes
/
index.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
import { useCallback, useEffect, useRef } from "react";
const useFileInput = (callback, opts) => {
const input = useRef();
useEffect(() => {
input.current = document.createElement("input");
input.current.type = "file";
}, []);
useEffect(() => {
if (input.current) {
if (opts) {
input.current.accept = opts.accept || "";
input.current.multiple = !!opts.multiple;
} else {
input.current.accept = "";
input.current.multiple = false;
}
}
}, [opts && opts.accept, opts && opts.multiple]);
useEffect(() => {
if (input.current) {
input.current.onchange = () => {
if (input.current && input.current.files) {
callback(input.current.files);
}
};
}
}, [callback]);
return useCallback(() => {
if (input.current) {
input.current.value = "";
input.current.click();
}
}, [input.current]);
};
export default useFileInput;