Reputation: 3125
A component of a library I'm using is essentially a wrapper around <input type=file>
, which manages the buttons to upload a new image, change it or remove it, while also providing a thumbnail of it. This is its simplified definition:
import defaultImage from "assets/images/default_image.jpg";
export default function ImageUpload(props) {
const { image, setImage } = props;
const [imagePreviewUrl, setImagePreviewUrl] = useState(defaultImage);
let fileInput = React.createRef();
const handleImageChange = e => {
e.preventDefault();
let reader = new FileReader();
const imageFile = e.target.files[0];
reader.onloadend = () => {
const image = reader.result;
setImage(image);
setImagePreviewUrl(image);
};
reader.readAsDataURL(imageFile);
};
const handleClick = () => {
fileInput.current.click();
};
const handleRemove = () => {
setImage("");
setImagePreviewUrl(defaultImage);
fileInput.current.value = null;
};
return (
<div>
<input
type="file"
onChange={handleImageChange}
ref={fileInput}
/>
<div>
<img src={imagePreviewUrl} />
</div>
<div>
{image === null ? (
<Button onClick={() => handleClick()}> {"Select image"} </Button>
) : (
<span>
<Button {...changeButtonProps} onClick={() => handleClick()}> Change </Button>
<Button {...removeButtonProps} onClick={() => handleRemove()}> Remove </Button>
</span>
)}
</div>
</div>
);
}
The parent is basically collecting this and other components's states and stores them into a redux store. All works well, until I try to clear the preview image.
As input
is not a controlled component in react, I'm not quite sure how to do that.
I though about passing the setImagePreviewUrl
as a prop, but I'm not entirely sure how to implement it.
How can I clear that preview image?
Upvotes: 0
Views: 1910
Reputation: 1242
If you try hiding the preview image than add condition like this:
<div>
{imagePreviewUrl && <img src={imagePreviewUrl} /> }
</div>
See full example by your code in the playground: https://jscomplete.com/playground/s524255
Upvotes: 1