Preview
Preview is a component that allows you to preview the content of a file before uploading it. Currently it supports previewing images. Preview is useful for users who want to see what they are uploading before they upload it. Preview can be used to show a thumbnail of the image, the file name, and the file size. Preview can also be used to show a preview of the image in a modal or a lightbox.
Installation
npm i @hookies/preview
Usage
usePreview
The usePreview
hook is used to generate a live preview of an uploaded image file. The hook takes a File
object as an argument and returns a URL string that can be used to display the preview.
import React, { useState } from "react";
import { usePreview } from "@hookies/preview";
const ImageUploader = () => {
const [data, setData] = useState<{ image?: File }>({});
const previewImageUrl = usePreview(data.image);
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files.length > 0) {
setData({ image: event.target.files[0] });
}
};
return (
<div>
<input type="file" accept="image/*" onChange={handleFileChange} />
{previewImageUrl && <img src={previewImageUrl} alt="Preview" width="200" />}
</div>
);
};
export default ImageUploader;