0

My Objective is to delete a particular file from the file list but when I want to delete the last file is being deleted instead of the required file.

Here is the code:

 {this.state.myFiles.map(file => (
        <p key={file.name}>
          {file.name} ({file.size} bytes)
          <button
            className={"material-icons delete"}
            onClick={() => this.handleRemoveFile(file.name)}
          >
            Remove file
          </button>
        </p>))}

Removing particular file from the files list:

handleRemoveFile = (fileName) => {
const myFiles = [...this.state.myFiles];
 myFiles.splice(myFiles.indexOf(fileName), 1)
        this.setState({ myFiles })
}

I couldn't able to delete a particular file, it is deleting the last one from the file list, can anyone help me in removing the particular file from the file list?

Thanks! in advance.

Yasharth Dubey
  • 500
  • 5
  • 18
Sandhya
  • 401
  • 2
  • 10
  • 24

1 Answers1

1

map gives you a second argument which is the index of the array.

 {this.state.myFiles.map((file,index) => (
        <p key={file.name}>
          {file.name} ({file.size} bytes)
          <button
            className={"material-icons delete"}
            onClick={() => this.handleRemoveFile(index)}
          >
            Remove file
          </button>
        </p>))}

Now you can use this index to filter the file

handleRemoveFile = (fileIndexToRemove) => {
   const updatedFiles = this.state.myFiles.filter((file, index) => index !== fileIndexToRemove)
   this.setState({ myFiles: updatedFiles  })
}
Shyam
  • 5,292
  • 1
  • 10
  • 20