Skip to content

Instantly share code, notes, and snippets.

@sairajchouhan
Created October 18, 2021 15:38
Show Gist options
  • Save sairajchouhan/33870634754bb99747b10825d6938f6a to your computer and use it in GitHub Desktop.
Save sairajchouhan/33870634754bb99747b10825d6938f6a to your computer and use it in GitHub Desktop.
React hook for image file upload
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