Home > Back-end >  File is replacing file, not adding in React (Next.js)
File is replacing file, not adding in React (Next.js)

Time:12-25

Please review my code first.

const test = () => {

const [files, setFiles] = useState ([]);

//I think I have to edit following statement.

const handleFile = (e) => {
   const newFiles = []
   for (let i=0; i < e.target.files.length; i  ) {
       newFiles.push(e.target.files[i])
    }
        setFiles(newFiles)
};

return (

   {files.map((file, index) => (
     <div>
       <div key={index}>
         <p>
         {file.name}
         </p>
         <Button size='small' onClick={() => {deleteSelectedFile(file.name)}}>
         Delete
         </Button>
       </div>
     </div>
    ))}

    <div>
        <label onChange={handleFile}>
            <input type='file' multiple />  Attach File
        </label>
    </div>

)

}

with handleFile statement, I can appropriately get the files.

However, when I upload one file at a time and then upload one file again,

the file is not added. the file replaces file.

There is not problem when I upload multiple time at once.

For example, I upload 'hello.jpg', and it renders well in the screen. Then, I upload 'goodbye.jpg', it renders well, but 'goodbye.jpg' replaces 'hello.jpg'.

Therefore, what I see is just 'goodbye.jpg' [button], not

'hello.jpg' [button] 'goodbye.jpg' [button]

.

I want my files to stacked up, without replacing.

I need some wisdom!

CodePudding user response:

In my opinion, you only need to spread the prev state values and the files during the change event.

import { useState } from "react";

export default function App() {
  const [files, setFiles] = useState([]);

  const handleChange = (e) => {
    // This is what you need
    setFiles((prev) => [...prev, ...Object.values(e.target.files)]);
  };

  return (
    <div>
      <label onChange={handleChange}>
        <input type="file" multiple />
      </label>
      {files.map((file) => {
        return <p>{file.name}</p>;
      })}
    </div>
  );
}

CodePudding user response:

how about you don't create a new variable for new files, you just set the state for the files since it's an array

setFiles(oldFile => [...oldFile,e.target.files[i]]);

If it's possible you can drop a codepen link

  • Related