Skip to content

Instantly share code, notes, and snippets.

@RodrigoTomeES
Created June 10, 2020 09:06
Show Gist options
  • Save RodrigoTomeES/06b27393f242c1ce75da57c5dc7077c1 to your computer and use it in GitHub Desktop.
Save RodrigoTomeES/06b27393f242c1ce75da57c5dc7077c1 to your computer and use it in GitHub Desktop.
Simple drag and drop file upload in React
import React, { Component } from 'react'
class FileUpload extends Component {
state = {
drag: false
}
dragCounter = 0
handleDrag = (e) => {
e.preventDefault()
e.stopPropagation()
}
handleDragIn = (e) => {
e.preventDefault()
e.stopPropagation()
this.dragCounter++
if (e.dataTransfer.items && e.dataTransfer.items.length > 0) {
this.setState({ drag: true })
}
}
handleDragOut = (e) => {
e.preventDefault()
e.stopPropagation()
this.dragCounter--
if (this.dragCounter === 0) {
this.setState({ drag: false })
}
}
handleDrop = (e) => {
e.preventDefault()
e.stopPropagation()
this.setState({ drag: false })
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
this.props.handleDrop(e.dataTransfer.files)
this.dragCounter = 0
}
}
render () {
return (
<div
style={{ display: 'inline-block', position: 'relative' }}
onDragEnter={this.handleDragIn}
onDragLeave={this.handleDragOut}
onDragOver={this.handleDrag}
onDrop={this.handleDrop}
>
{this.state.drag &&
<div
style={{
border: 'dashed grey 4px',
backgroundColor: 'rgba(255,255,255,.8)',
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
zIndex: 9999
}}
>
<div
style={{
position: 'absolute',
top: '50%',
right: 0,
left: 0,
textAlign: 'center',
color: 'grey',
fontSize: 36
}}
>
<div>drop here :)</div>
</div>
</div>}
{this.props.children}
</div>
)
}
}
export default FileUpload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment