Search code examples
javascriptreactjstypescriptreact-dropzone

Image thumb disappear when I remove first array element


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: https://stackblitz.com/edit/react-ts-jej14g?file=App.tsx

Example


Solution

  • 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