Home > OS >  After removing the image cannot input same image again
After removing the image cannot input same image again

Time:08-27

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>

CodePudding user response:

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

const [image, setImage] = useState<any>("noImage");
const inputRef = useRef<HTMLInputElement>(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>

CodePudding user response:

I think you should reset currentTarget.value like this.

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

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