-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathUiFileInputButton.tsx
81 lines (71 loc) · 2.1 KB
/
UiFileInputButton.tsx
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
73
74
75
76
77
78
79
80
81
import React from 'react';
export interface IProps {
/**
* A string that defines the file types the file input should accept.
* This string is a comma-separated list of unique file type specifiers.
*
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#accept
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#Unique_file_type_specifiers
*/
acceptedFileTypes?: string;
/**
* When allowMultipleFiles is true, the file input allows the user to select more than one file.
*
* https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/multiple
*
* @default false
*/
allowMultipleFiles?: boolean;
/**
* Text to display as the button text
*/
label: string;
/**
* Handler passed from parent
*
* When the file input changes a FormData object will be send on the first parameter
*/
onChange: (formData: FormData) => void;
/**
* The name of the file input that the backend is expecting
*/
uploadFileName: string;
}
export const UiFileInputButton: React.FC<IProps> = (props) => {
const fileInputRef = React.useRef<HTMLInputElement | null>(null);
const formRef = React.useRef<HTMLFormElement | null>(null);
const onClickHandler = () => {
fileInputRef.current?.click();
};
const onChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
if (!event.target.files?.length) {
return;
}
const formData = new FormData();
Array.from(event.target.files).forEach((file) => {
formData.append(event.target.name, file);
});
props.onChange(formData);
formRef.current?.reset();
};
return (
<form ref={formRef}>
<button type="button" onClick={onClickHandler}>
{props.label}
</button>
<input
accept={props.acceptedFileTypes}
multiple={props.allowMultipleFiles}
name={props.uploadFileName}
onChange={onChangeHandler}
ref={fileInputRef}
style={{ display: 'none' }}
type="file"
/>
</form>
);
};
UiFileInputButton.defaultProps = {
acceptedFileTypes: '',
allowMultipleFiles: false,
};