react-dropzone icon indicating copy to clipboard operation
react-dropzone copied to clipboard

Make it possible to remove file from acceptedFiles state

Open claytonfbell opened this issue 7 years ago • 42 comments

Do you want to request a feature or report a bug?

  • [ ] I found a bug
  • [x] I want to propose a feature

What is the current behavior? No way to remove file from the acceptedFiles state array.

If this is a feature request, what is motivation or use case for changing the behavior? it would be nice to allow user to remove files with a trash button from the acceptedFiles state array. Please forgive me if this functionality exists, I did not find it in examples or StackOverflow and I'm still learning to work with hooks.

claytonfbell avatar Mar 26 '19 22:03 claytonfbell

@claytonfbell I think this is out of the scope of dropzone. It's up to you to alter the files in whatever way you need/want.

Furthermore, the dropzone can be used as a headless component or a hook, meaning there is no UI rendered, therefore, we cannot add any delete buttons. You're perhaps referring to the examples, but note that those are not part of the dropzone lib.

If you have further issues, feel free to report it.

rolandjitsu avatar Mar 27 '19 00:03 rolandjitsu

I see, thanks for getting back. I missed the response until now.

I didn't mean to propose adding any UI component. But I want to mutate the acceptedFiles state array that is returned from the useDropzone hook. Like if we added a clearFiles function that could also be returned from the hook. The "Clear" UI button on my component's end would call it onClick={clearFiles}.

    // line 743 - added function to useDropdown's return
    clearFiles: () => {
      dispatch({ type: 'setFiles' , acceptedFiles: [], rejectedFiles: []})
    }

Maybe I'm missing an obvious way to change the state of "acceptedFiles" returned from the hook.

Thank you, this is a terrific library.

claytonfbell avatar Apr 02 '19 20:04 claytonfbell

@claytonfbell this can be done in the user land, or maybe I'm missing something 😕 It could help if you could provide an example illustrating your use case.

rolandjitsu avatar Apr 03 '19 00:04 rolandjitsu

Thank you again!

I've taken the existing Basic example and added a Remove File button next to each file, as well as the addition of a Remove All button.

dropzone

import React from 'react';
import {useDropzone} from 'react-dropzone';

function Basic(props) {
  const {acceptedFiles, getRootProps, getInputProps, inputRef} = useDropzone();

  const removeFile = (file) => () => {
    console.log('removeFile...')
    acceptedFiles.splice(acceptedFiles.indexOf(file), 1)
    console.log(acceptedFiles)
  }

  const removeAll = () => {
    console.log('removeAll...')
    acceptedFiles.length = 0
    acceptedFiles.splice(0, acceptedFiles.length)
    inputRef.current.value = ''
    console.log(acceptedFiles)
  }

  const files = acceptedFiles.map(file => (
    <li key={file.path}>
      {file.path} - {file.size} bytes <button onClick={removeFile(file)}>Remove File</button>
    </li>
  ));

  return (
    <section className="container">
      <div {...getRootProps({className: 'dropzone'})}>
        <input {...getInputProps()} />
        <p>Drag 'n' drop some files here, or click to select files</p>
      </div>
      <aside>
        <h4>Files</h4>
        <ul>{files}</ul>
      </aside>
      { files.length > 0 && <button onClick={removeAll}>Remove All</button> }
    </section>
  );
}

export default Basic

claytonfbell avatar Apr 03 '19 17:04 claytonfbell

After working with this more I work around by creating my own useState. Not sure if this is the best way, but maybe this can be helpful to others.

import React, { useState, useCallback } from "react"
import { useDropzone } from "react-dropzone"

function Basic(props) {
  const [myFiles, setMyFiles] = useState([])

  const onDrop = useCallback(acceptedFiles => {
    setMyFiles([...myFiles, ...acceptedFiles])
  }, [myFiles])

  const { getRootProps, getInputProps } = useDropzone({
    onDrop,
  })

  const removeFile = file => () => {
    const newFiles = [...myFiles]
    newFiles.splice(newFiles.indexOf(file), 1)
    setMyFiles(newFiles)
  }

  const removeAll = () => {
    setMyFiles([])
  }

  const files = myFiles.map(file => (
    <li key={file.path}>
      {file.path} - {file.size} bytes{" "}
      <button onClick={removeFile(file)}>Remove File</button>
    </li>
  ))

  return (
    <section className="container">
      <div {...getRootProps({ className: "dropzone" })}>
        <input {...getInputProps()} />
        <p>Drag 'n' drop some files here, or click to select files</p>
      </div>
      <aside>
        <h4>Files</h4>
        <ul>{files}</ul>
      </aside>
      {files.length > 0 && <button onClick={removeAll}>Remove All</button>}
    </section>
  )
}

export default Basic

claytonfbell avatar Apr 09 '19 19:04 claytonfbell

Hi I am using default rejected files from the dependency. I need to remove the rejected file, can you please explain me

dropzone.txt

gundojuprashanth avatar Aug 05 '19 09:08 gundojuprashanth

Imo, this should be a part of package api.

fyodoriv avatar Sep 03 '19 16:09 fyodoriv

I hope this example will be of some help to you guys (Used DataTransfer API)

aimdevlee avatar Jan 21 '20 04:01 aimdevlee

@claytonfbell , thank you.

oneadera avatar Jan 23 '20 09:01 oneadera

Is there really no built-in way of doing this?

aaj avatar Jan 29 '20 19:01 aaj

@aaj no. But seeing that more ppl want this, I think someone should make a PR as I don't have the time to do it.

rolandjitsu avatar Jan 30 '20 00:01 rolandjitsu

@rolandjitsu After writing that comment I figured out a way to do it in my own code, and honestly I've changed my mind about this. acceptedFiles is only available during the onDrop callbacks. It doesn't represent a persistent list of selected files, so it doesn't really make sense to have a way of clearing that list. I essentially did what @claytonfbell did, which is the only logical way to do it (keeping files in your own state).

aaj avatar Jan 30 '20 17:01 aaj

@claytonfbell , thank you.

rcasari1987 avatar May 09 '20 22:05 rcasari1987

I hope this example will be of some help to you guys (Used DataTransfer API)

This example does not work with dropped files since dropping does not set the files on the input...

wmadam avatar May 14 '20 20:05 wmadam

After working with this more I work around by creating my own useState. Not sure if this is the best way, but maybe this can be helpful to others.

import React, { useState, useCallback } from "react"
import { useDropzone } from "react-dropzone"

function Basic(props) {
  const [myFiles, setMyFiles] = useState([])

  const onDrop = useCallback(acceptedFiles => {
    setMyFiles([...myFiles, ...acceptedFiles])
  })

  const { getRootProps, getInputProps } = useDropzone({
    onDrop,
  })

  const removeFile = file => () => {
    const newFiles = [...myFiles]
    newFiles.splice(newFiles.indexOf(file), 1)
    setMyFiles(newFiles)
  }

  const removeAll = () => {
    setMyFiles([])
  }

  const files = myFiles.map(file => (
    <li key={file.path}>
      {file.path} - {file.size} bytes{" "}
      <button onClick={removeFile(file)}>Remove File</button>
    </li>
  ))

  return (
    <section className="container">
      <div {...getRootProps({ className: "dropzone" })}>
        <input {...getInputProps()} />
        <p>Drag 'n' drop some files here, or click to select files</p>
      </div>
      <aside>
        <h4>Files</h4>
        <ul>{files}</ul>
      </aside>
      {files.length > 0 && <button onClick={removeAll}>Remove All</button>}
    </section>
  )
}

export default Basic

@claytonfbell doesn't useCallback requires a dependency array in order to execute? https://reactjs.org/docs/hooks-reference.html#usecallback

waldothedeveloper avatar May 21 '20 20:05 waldothedeveloper

Yes, I’m unsure why that was missing, good catch. I’ve added a dependency array.

claytonfbell avatar May 22 '20 03:05 claytonfbell

@claytonfbell, thanks... thanks.. thank you!

ijayoa avatar Jul 08 '20 17:07 ijayoa

@claytonfbell Thanks sir.

lsandoval0000 avatar Aug 05 '20 15:08 lsandoval0000

Tracking the file list using local state works in most cases, but because the local state isn't tied to the <input>'s value attribute (a FileList), removing a file from local state does not remove the file from the <input>. So when I add a file, "remove" it (from local state), and then try to add the same file again, onDrop does not fire because the file is already present in the <input>'s FileList.

Because onDrop doesn't fire, the file does not get added back to my local state.

I am unsure how to fix this bug without a helper method allowing me to clear/reset the <input>

EDIT: I resorted to unmounting and remounting the <input> when user removes the file. That gives us a fresh input to work with, which will accept the original file without issues

  const [isInputMounted, setIsInputMounted] = useState(true);
  useEffect(
    function remountInput() {
      if (!isInputMounted) {
        setIsInputMounted(true);
      }
    },
    [isInputMounted]
  );

  function handleRemoveFile() {
    setIsInputMounted(false);
    setFile(null);
  }

  const { getRootProps, getInputProps, inputRef } = useDropzone({
    onDrop,
  });

  return (
    <div>
      {isInputMounted && (
        <input
          {...getInputProps({
            name,
          })}
          data-testid="InputFileUploadField_input"
        />
      )}
    </div>
  )


madisonbullard avatar Nov 12 '20 22:11 madisonbullard

I hope this example will be of some help to you guys (Used DataTransfer API)

This is the approach from @aimdevlee solved this for me, I was uploading files to a server in a useEffect based on acceptedFiles changing, there were other dependencies to this useEffect and when they changed it would re-upload the files! Moving to an intermediate local state 'buffer' of filesToUpload and then clearing that in the post requests .then() and .catch() block solved this problem.

Ideally it would have been nice to have just done setAcceptedFiles([]) but the above worked well

simonbarker avatar Jan 06 '21 09:01 simonbarker