-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Expand file tree
/
Copy pathuseSingleFileInput.ts
More file actions
65 lines (55 loc) · 1.53 KB
/
useSingleFileInput.ts
File metadata and controls
65 lines (55 loc) · 1.53 KB
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
import { useEffectEvent } from '@rocket.chat/fuselage-hooks';
import { useRef, useEffect } from 'react';
export const useSingleFileInput = (
onSetFile: (file: File, formData: FormData) => void,
fileField = 'image',
options?: {
fileType?: string;
},
): [onClick: () => void, reset: () => void] => {
const ref = useRef<HTMLInputElement>();
const fileType = options?.fileType || 'image/*';
useEffect(() => {
const fileInput = document.createElement('input');
fileInput.setAttribute('type', 'file');
fileInput.setAttribute('style', 'display: none');
document.body.appendChild(fileInput);
ref.current = fileInput;
return (): void => {
ref.current = undefined;
fileInput.remove();
};
}, []);
useEffect(() => {
const fileInput = ref.current;
if (!fileInput) {
return;
}
fileInput.setAttribute('accept', fileType);
}, [fileType]);
useEffect(() => {
const fileInput = ref.current;
if (!fileInput) {
return;
}
const handleFiles = (): void => {
if (!fileInput?.files?.length) {
return;
}
const formData = new FormData();
formData.append(fileField, fileInput.files[0]);
onSetFile(fileInput.files[0], formData);
};
fileInput.addEventListener('change', handleFiles, false);
return (): void => {
fileInput.removeEventListener('change', handleFiles, false);
};
}, [fileField, fileType, onSetFile]);
const onClick = useEffectEvent(() => ref?.current?.click());
const reset = useEffectEvent(() => {
if (ref.current) {
ref.current.value = '';
}
});
return [onClick, reset];
};