Skip to content

Instantly share code, notes, and snippets.

@codeBelt
Last active July 15, 2021 12:44
Show Gist options
  • Save codeBelt/4f6a47e2c1c7c1c16fed4f4b871f5852 to your computer and use it in GitHub Desktop.
Save codeBelt/4f6a47e2c1c7c1c16fed4f4b871f5852 to your computer and use it in GitHub Desktop.
export interface IProps {
acceptedFileTypes?: string;
allowMultipleFiles?: boolean;
label: string;
onChange: (formData: FormData) => void;
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,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment