Upload and display an image on UI
const Component = () => {
const [imgUrl, setImgUrl] = useState();
const handleChangeImg = e => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onloadend = finishedEvent => {
const result = finishedEvent.currentTarget.result;
setImgUrl(result);
};
reader.readAsDataURL(file);
};
const handleDeleteImg = () => setImgUrl(null);
return(
<input type="file" accept="image/*" onChange={`handleChangeImg`} />
{imgUrl && (
<div>
<img src={imgUrl} width="50px" height="50px" alt="Tweet" />
<button onClick={handleDeleteImg}>Clear</button>
</div>
)}
);
}