-2

I am trying to upload multiple images in React as array. It is uploading the images but suppose I select 2 images it uploads only one image and gives other image is undefined. Here's the code:

 const [labImages, setLabImages] = useState([])

  const handleLabImagesUpload = (e) => {
    setLabImages([...labImages, e.target.files[0]])
  }

const handleSubmit = async (e) => {
    e.preventDefault()
 console.log(labImages)
}

//JSX Part
<label className="text-base xs:text-xl w-[180px] xs:w-[210px] text-white border-[1px] font-bold border-black px-4 py-[2px] rounded">
              <input
                type="file"
                className="cursor-pointer"
                onClick={handleLabImagesUpload}
              />
              Upload Lab Images
</label>

<button
            className="bg-secondary text-white font-bold text-xl px-8 rounded py-1 lg:px-12"
            onClick={handleSubmit}
 > Submit </button>


1 Answers1

1

As mentioned in this answer, the input element can accept multiple files if given the multiple attribute.

Edit:

onClick on the input will execute as soon as the input element is clicked, not when you select the files. At that point in time, e.target.files[0] will be undefined.

To access the files after a value has been selected, try the onChange event instead.

Also, why manually append the first file? If e.target.files is an array, you could just use the array directly.

AviusX
  • 374
  • 2
  • 12
  • It is selecting multiple file but on submitting when that `handleSubmit` runs, it logs "undefined" in the console – Preet Sojitra Jan 09 '23 at 18:12
  • what is `handleLabImagesUpload` doing? Where are you actually setting the `labImages` state? You initialize it with an empty array but I never see it getting updated. – AviusX Jan 09 '23 at 18:18
  • ohh so sorry. I have updated the code, I missed to put that part of the code – Preet Sojitra Jan 09 '23 at 19:05