I'm currently working on React. The on-Click event on <Input type="file" />
opens the explorer where I can select and upload files, the image file name is displayed next to the upload button, to the S3, I have a remove button next to the upload button, on-Click action on remove button displays the confirmation modal to remove the upload files, but the file name next to the input menu isn't updated and I can't upload the same file which I had uploaded.
Upload Function
const uploadFile = (e: any) => {
if (e.target.files[0]) {
const formData = new FormData();
///
PostImgFile(formData); // POST Methods to S3
}
}
For Confirm Modal Action
const deleteFile = () => {
hideConfirmModal('confirmDeletion')
if(imageDetails?.imgId){
DeleteImgFile(). //Delete Method
}}
<input type="file" id="imgFile" style={{ display: 'none' }} onChange={uploadFile} />
<input type="button" onClick={() => confirmModal('confirmDelete')}. hidden={fileName?.length < 1} />
CodePudding user response:
All you need is to set the value back to null, i.e by using useRef
we have to set the property of the input value null. I wish I had more input but I hope the solution below works.
import React, { useState, useRef } from "react";
function App() {
const hiddenFileInput = useRef(null);
const [image, setImage] = useState(null);
function removeFile() {
hiddenFileInput.current.value = null;
setImage(null);
}
const onChange = (e) => {
const fileUploaded = e.target.files[0];
if (!fileUploaded) return;
setImage(fileUploaded);
};
return (
<>
<h1>Home</h1>
<input type="file" ref={hiddenFileInput} onChange={onChange} />
<button onClick={removeFile}>Remove Image</button>
{image && (
<img
src={URL.createObjectURL(image)}
alt={image.name}
/>
)}
</>
);
}