Skip to content

Instantly share code, notes, and snippets.

@maruware
Created September 4, 2019 07:30
Show Gist options
  • Save maruware/329ec54328cfaae874b81953c865ccc0 to your computer and use it in GitHub Desktop.
Save maruware/329ec54328cfaae874b81953c865ccc0 to your computer and use it in GitHub Desktop.
Material UI - Basic File Input
import React from 'react'
import Button from '@material-ui/core/Button'
export interface BasicFileInputProps {
label: string
accept: string
value: File | null
onChange: (file: File | null) => void
}
const BasicFileInput: React.FC<BasicFileInputProps> = ({
label,
accept,
value,
onChange
}) => {
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files) {
onChange(null)
return
}
const file = e.target.files[0]
if (!file) {
onChange(null)
return
}
onChange(file)
}
return (
<span>
<Button variant="outlined" component="label">
{label}
<input
onChange={handleChange}
type="file"
accept={accept}
style={{ display: 'none' }}
/>
</Button>
{value && <span style={{ marginLeft: 8 }}>{value.name}</span>}
</span>
)
}
export default BasicFileInput
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment