react-dropit
Version:
Uploading files is now easier :))
83 lines (53 loc) • 1.37 kB
JavaScript
class Thumb extends React.Component {
state = { url: '', onerror: false, defaultUrl: '' }
reader = null
componentDidMount () {
this.initReader()
this.updateUrl()
}
initReader = () => {
this.reader = new FileReader
this.reader.addEventListener('load', () => {
this.setState({url: this.reader.result})
})
}
updateUrl = () => {
const { type, value: file } = this.props
if (typeof file === 'string') {
this.setState({url: file})
} if (typeof file === 'object') {
if (file.type.indexOf('image') === 0) {
this.reader.readAsDataURL(file)
}
}
}
onError = () => {
if (this.state.onerror) return;
this.setState({onerror: true, url: ''})
}
renderInfo = () => {
const { value: file } = this.props
if (typeof file === 'object') {
const { name, size } = file
return (
<div className="react-dropit-tn-info">
<div>{name}</div>
<div>{Math.floor(size / 1024)} kb</div>
</div>
)
}
}
render () {
const { percent, className, value: file, id, removeFile } = this.props
return (
<div className={className || 'react-dropit-thumbnail'}>
<div>
<img width={150} src={this.state.url || this.state.defaultUrl} onError={this.onError} />
</div>
{this.renderInfo()}
<button onClick={() => removeFile(id)}>Remove</button>
</div>
)
}
}
export default Thumb