useImagePreview Hook
A hook for previewing an image file
Code Snippet
useImagePreview.ts
import { useState, useEffect } from 'react';
export default function useImagePreview(imageFile: File | null) {
const [previewSrc, setPreviewSrc] = useState('');
useEffect(() => {
if (!imageFile) return;
const reader = new FileReader();
reader.onloadend = () => {
setPreviewSrc(reader.result as string);
};
reader.readAsDataURL(imageFile);
return () => {
reader.abort();
};
}, [imageFile]);
return previewSrc;
}
Usage
Assuming that you already have a markup (a file input and an image element), use the hook as follows:
- Create a state for your image file like this:
const [imageFile, setImageFile] = useState<File | null>(null);
- Pass
imageFile
as the argument for the hook and use its return valuepreviewSrc
:
const previewSrc = useImagePreview(imageFile);
- Assign the value of
previewSrc
to your image'ssrc
:
<img
src={previewSrc}
alt='a sample preview'
width='100%'
height='100%'
style={{ objectFit: 'cover' }} // the style depends on your requirements
/>