I am creating an image(s) upload component in React. Every time the file input field changes I am updating the images
state. Below the input field I am trying to loop through the images and log their names in the console. However, as soon as I select an image, I get the error TypeError: images.map is not a function.
Here is my code:
import React, { useState } from 'react';
const ImagesInput = (props) => {
const [images, setImages] = useState([]);
const imageInputChange = (e) => {
setImages(e.target.files)
}
return (
<div>
<input {...props} type="file" onChange={imageInputChange} multiple />
{images.map((image) => {
console.log(image)
})}
</div>
)
}
export default ImagesInput;
CodePudding user response:
The value of e.target.files is an array-like not an actual array. Just convert it to array before passing to setImages, like
setImages([...e.target.files])
CodePudding user response:
Before
setImages(e.target.files)
Try to add a condition like this, make sure e.target.files is the image arr you want
if(e.target.files){
setImages(e.target.files)
}