Home > Back-end >  Image thumb disappear when I remove first array element
Image thumb disappear when I remove first array element

Time:10-01

I'm trying to make an image drag n drop with react-dropzone, and when I drop a image at dropzone, it is stored in react state, in a files array.

The problem is when i remove an image from array, the thumbs of the remaining items disappear.

Here is a example: Example

CodePudding user response:

The problem is in your handleDeleteImage method

All you have to do is

  • clone the existing array
  • revoke the URL at the requested index
  • remove the element
  • update the files state
 function handleDeleteImage(index: number) {
    const filesArray = [...files];
    URL.revokeObjectURL(filesArray[index].preview);
    filesArray.splice(index, 1);
    setFiles(filesArray);
  }

Working demo: https://stackblitz.com/edit/react-ts-pxxyng?file=App.tsx

  • Related