0

How to show the multiple files using select field, want to display the no of files which i have been selected but it is only showing single file

const [lessonImage, setLessonImage] =  React.useState([]);

const handleLessonImage = (event) => {
  setLessonImage(event.target.files);
} 

 <input 
    type="file" 
    onChange={handleLessonImage}
    multiple
 />

1 Answer 1

1

You can access name of file from File Object.

Link to CodeSandBox


import React from "react";

export default function App() {
  const [lessonImage, setLessonImage] = React.useState([]);

  const handleLessonImage = (event) => {
    const data = [];
    for (let i = 0; i < event.target.files.length; i++) {
      data.push(event.target.files[i]);
    }
    setLessonImage((old)=> […old,data]);
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <input type="file" onChange={handleLessonImage} multiple />

      {lessonImage.map((item, index) => {
        return (
          <div key={index}>
            <h3>{item.name}</h3>
          </div>
        );
      })}
    </div>
  );
}


Sign up to request clarification or add additional context in comments.

3 Comments

while adding other one, previous file is removing
@Mohan I have updated the code. Please accept and upvote my answer if it solves your problem.
I added setLessonImage((old)=> [...old,...data]) it worked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.