Awantha Irushan
Awantha Irushan

Reputation: 137

After removing the image cannot input same image again

I created an image upload, and remove the uploaded image. Once upload the image we can remove it again and input another image. But I can't input the same image agin.

const [image, setImage] = useState<any>("noImage");
const [isImageUploaded, setIsImageUploaded] = useState<boolean>(false);

const handleImageChange = (event: any) => {
  setImage(URL.createObjectURL(event.target.files[0]));
  setIsImageUploaded(true);
};

const handleOnImageRemoveClick = () => {
  setIsImageUploaded(false);
  setImage("noImage");
};
<span>
  <input type="file" className="d-none" onChange={handleImageChange} disabled={isImageUploaded} />
  {isImageUploaded ? (
    <div>
      <div className="d-flex justify-content-center">
        <Button variant="warning" onClick={handleOnImageRemoveClick}>
          Remove Image
        </Button>
      </div>
    </div>
  ) : (
    <div>
      <p>Click to upload the image</p>
    </div>
  )}
</span>

Upvotes: 5

Views: 1479

Answers (2)

Youssouf Oumar
Youssouf Oumar

Reputation: 45825

You are not emptying your input correctly. I would recommend you to use a ref with useRef. Also, you can shorten your code by only having the image state, like so:

const [image, setImage] = useState<any>("noImage");
const inputRef = useRef<any>(null); // import useRef from react

const handleImageChange = (event: any) => {
  setImage(URL.createObjectURL(event.target.files[0]));
};

const handleOnImageRemoveClick = () => {
  setImage("noImage");
  inputRef.current.value="";
};
<span>
  <input ref={inputRef} type="file" className="d-none" onChange={handleImageChange} disabled={image !== "noImage"} />
  {image !== "noImage" ? (
    <div>
      <div className="d-flex justify-content-center">
        <Button variant="warning" onClick={handleOnImageRemoveClick}>
          Remove Image
        </Button>
      </div>
    </div>
  ) : (
    <div>
      <p>Click to upload the image</p>
    </div>
  )}
</span>

Upvotes: 9

k0uh0t
k0uh0t

Reputation: 156

I think you should reset currentTarget.value like this.

<input
  ...
  onClick={(event)=> { 
    event.currentTarget.value = null
  }}
/>

// TS
onClick={(event) => {
  (event.target as HTMLInputElement).value = '';
}}

Upvotes: 1

Related Questions