input type="file" image, preview, 미리보기
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYYAAAECCAYAAAD6oXArAAAMP2lDQ1BJQ0M......
~code~
// 1
const [imgFile, setImgFile] = useState<File | null>();
const [preview, setPreview] = useState<string | null>("");
// 2
const onChangeImg = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files !== null) {
const file = event.target.files[0];
if (file && file.type.substring(0, 5) === "image") {
setImgFile(file);
} else {
setImgFile(null);
}
}
};
// 3
useEffect(() => {
if (imgFile) {
const reader = new FileReader();
reader.onloadend = () => {
setPreview(reader.result as string);
};
reader.readAsDataURL(imgFile);
} else {
setPreview(null);
}
}, [imgFile]);
// 4
<input
name="img"
type="file"
accept="image/*"
onChange={onChangeImg}
className="hidden"
/>
<img src={preview as string} />