Last active
July 10, 2021 08:53
-
-
Save tacigar/854702f334d76d5829543e3c064c1402 to your computer and use it in GitHub Desktop.
Very simple image uploader
This file contains 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, { useCallback } from 'react'; | |
import { useState } from 'react'; | |
interface ImageUploaderProps {} | |
const ImageUploader: React.FC<ImageUploaderProps> = () => { | |
const [imageUrl, setImageUrl] = useState(''); | |
const handleDrop = useCallback((event: React.DragEvent<HTMLDivElement>) => { | |
event.preventDefault(); | |
const { dataTransfer } = event; | |
let file: File | undefined; | |
for (let i = 0; i < dataTransfer.items.length; i++) { | |
const f = dataTransfer.items[i].getAsFile(); | |
if (f) file = f; | |
} | |
if (!file) return; | |
const reader = new FileReader(); | |
reader.readAsDataURL(file); | |
reader.onload = () => { | |
if (typeof reader.result === 'string') { | |
setImageUrl(reader.result); | |
} | |
}; | |
}, []); | |
const handleDragOver = useCallback((event: React.DragEvent<HTMLDivElement>) => { | |
event.stopPropagation(); | |
event.preventDefault(); | |
}, []); | |
return ( | |
<div> | |
<div | |
style={{ | |
width: '240px', | |
height: '120px', | |
display: 'flex', | |
alignItems: 'center', | |
justifyContent: 'center', | |
border: '1px solid', | |
borderRadius: '8px', | |
}} | |
onDrop={handleDrop} | |
onDragOver={handleDragOver} | |
> | |
Drag & Drop your image here | |
</div> | |
{imageUrl && <img src={imageUrl} alt="uploaded" />} | |
</div> | |
); | |
}; | |
export default ImageUploader; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment