Created
September 13, 2019 15:46
-
-
Save afraser/f3433ff08a923cea6e4556999546d67c to your computer and use it in GitHub Desktop.
FileDropzone
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 React, { useState, useEffect, useRef } from 'react' | |
import cx from 'classnames' | |
import css from './FileDropzone.sass' | |
export function FileDropzone ({ onDrop, children }) { | |
const [dragging, setDragging] = useState(0) | |
const dropRef = useRef() | |
const handleDrag = evt => { | |
evt.preventDefault() | |
evt.stopPropagation() | |
} | |
const handleDragIn = evt => { | |
evt.preventDefault() | |
evt.stopPropagation() | |
setDragging(evt.dataTransfer.items.length) | |
} | |
const handleDragOut = evt => { | |
evt.preventDefault() | |
evt.stopPropagation() | |
setDragging(0) | |
} | |
const handleDrop = evt => { | |
evt.preventDefault() | |
evt.stopPropagation() | |
setDragging(0) | |
if (evt.dataTransfer.files && evt.dataTransfer.files.length > 0) { | |
onDrop(evt.dataTransfer.files) | |
evt.dataTransfer.clearData() | |
} | |
} | |
useEffect(() => { | |
const div = dropRef.current | |
div.addEventListener('dragenter', handleDragIn) | |
div.addEventListener('dragleave', handleDragOut) | |
div.addEventListener('dragover', handleDrag) | |
div.addEventListener('drop', handleDrop) | |
return () => { | |
const div = dropRef.current | |
div.removeEventListener('dragenter', handleDragIn) | |
div.removeEventListener('dragleave', handleDragOut) | |
div.removeEventListener('dragover', handleDrag) | |
div.removeEventListener('drop', handleDrop) | |
} | |
}) | |
const placeholder = children || ( | |
<div className={css.placeholder}> | |
<p>Drag and drop files here to upload.</p> | |
</div> | |
) | |
return ( | |
<div | |
className={cx(css.dropzone, {[css.dragging]: dragging})} | |
ref={dropRef}> | |
<div className={css.placeholder}> | |
{ placeholder } | |
</div> | |
</div> | |
) | |
} |
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
.dropzone | |
border: 4px dashed #ccc | |
width: 800px | |
min-height: 400px | |
margin: 0 auto | |
display: flex | |
align-items: center | |
justify-content: center | |
color: #666 | |
font-size: 18px | |
&.dragging | |
.placeholder | |
pointer-events: none | |
opacity: 0.5 | |
.placeholder | |
text-align: center |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment