Let's assume that you want to drag and drop a local image to a React component:
jsxconst DragDrop = () => { const [img, setImg] = useState(null) const readImage = (e) => { e.preventDefault() e.stopPropagation() let file = e.dataTransfer.files[0] let reader = new FileReader() reader.readAsDataURL(file) reader.onload = () => setImg(reader.result) } return( <div className = 'Upload'> <div className = 'Drag' onDragOver = {e => e.preventDefault()} onDrop = {readImage}> {img ? <img src = {img}/> : 'Drag an image here'} </div> </div> ) }
Combine onDragOver
and onDrop
events and the FileReader()
API. See a live example at CodePen.
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.