Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

389
Views
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,

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!

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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>
  );
}
about 4 years ago · Santiago Trujillo Report

0

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

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!