Created
May 23, 2022 12:04
-
-
Save sergiycheck/23df854989a55e17276b7f52954e0cd3 to your computer and use it in GitHub Desktop.
photo preview component with react, chakra and FileReader
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
export const PhotoPreviewExcerpt = ({ | |
file, | |
setSelectedFiles, | |
}: { | |
file: File; | |
setSelectedFiles: React.Dispatch<React.SetStateAction<File[] | null | undefined>>; | |
}) => { | |
const fileReaderRef = React.useRef<FileReader>(); | |
const [photoSrc, setPhotoSrc] = React.useState<string>(); | |
React.useEffect(() => { | |
fileReaderRef.current = new FileReader(); | |
const fileReader = fileReaderRef.current; | |
function handleEvent(ev: ProgressEvent<FileReader>) { | |
if (fileReader.result) { | |
const photoSrc = fileReader.result as unknown as string; | |
setPhotoSrc(photoSrc); | |
} | |
} | |
if (fileReader.readyState === FileReader.EMPTY) { | |
fileReader.readAsDataURL(file); | |
} | |
fileReader.addEventListener('load', handleEvent); | |
return () => { | |
fileReader.removeEventListener('load', handleEvent); | |
}; | |
}, [file]); | |
return ( | |
<Box position="relative" p="2" mt={10}> | |
<Button | |
position="absolute" | |
right="-10" | |
top="-10" | |
onClick={(e) => { | |
setSelectedFiles((prevFiles) => prevFiles?.filter((f) => f.name !== file.name)); | |
}} | |
> | |
<CloseIcon></CloseIcon> | |
</Button> | |
<Image | |
boxSize="sm" | |
rounded="md" | |
objectFit="cover" | |
src={photoSrc} | |
alt={`${file.name}`} | |
fallbackSrc="https://via.placeholder.com/150" | |
/> | |
</Box> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment