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>
CodePudding user response:
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.