Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

File is replacing file, not adding in React (Next.js)

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading