Skip to content

Instantly share code, notes, and snippets.

@reecelucas
Created July 11, 2019 11:19
Show Gist options
  • Save reecelucas/ed71300089b30227a8c9c565e70d69ad to your computer and use it in GitHub Desktop.
Save reecelucas/ed71300089b30227a8c9c565e70d69ad to your computer and use it in GitHub Desktop.
Custom React file select component
import * as React from 'react';
interface Props extends React.HTMLProps<HTMLInputElement> {
onFileSelect: (file: File) => void;
}
const FileInput = ({ onFileSelect, ...props }: Props) => {
const inputRef = React.useRef<HTMLInputElement>();
const onChange = (event: React.ChangeEvent) => {
const fileInput = event.target as HTMLInputElement;
const file = fileInput.files && fileInput.files[0];
if (!file) {
return;
}
onFileSelect(file);
inputRef.current.value = ''; // Reset input value
};
const onClick = () => {
if (inputRef.current) {
inputRef.current.click();
}
};
return (
<>
<button onClick={onClick}>Select a file</button>
<input
{...props}
type={'file'}
onChange={onChange}
style={{ display: 'none' }}
ref={inputRef}
/>
</>
);
};
export default FileInput;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment