-
-
Save elshahat/a7e0617bad357309151f517d2a914235 to your computer and use it in GitHub Desktop.
Custom React file select component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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