Created
October 18, 2021 15:38
-
-
Save sairajchouhan/33870634754bb99747b10825d6938f6a to your computer and use it in GitHub Desktop.
React hook for image file upload
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 { useEffect, useState } from 'react' | |
// fill the array with the image type you want to allow | |
const allowedImageTypes = ['image/jpeg', 'image/png'] | |
export const useFileUpload = () => { | |
const [selectedFile, setSelectedFile] = useState<Blob | null>(null) | |
const [previewUrl, setPreviewUrl] = useState<string | null>(null) | |
const [error, setError] = useState<string | null>(null) | |
useEffect(() => { | |
if (selectedFile) { | |
setPreviewUrl(URL.createObjectURL(selectedFile)) | |
} | |
}, [selectedFile]) | |
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => { | |
const files = e.target.files | |
if (files) { | |
const file = files[0] | |
console.log(file.type) | |
if (file && allowedImageTypes.includes(file.type)) { | |
setSelectedFile(file) | |
} else { | |
setError('*Please select a valid image file') | |
} | |
} | |
} | |
const resetFile = () => { | |
setSelectedFile(null) | |
setPreviewUrl(null) | |
setError(null) | |
} | |
return { | |
selectedFile, | |
previewUrl, | |
handleFileChange, | |
resetFile, | |
error, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment