0

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;

2 Answers 2

2

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])

Read here about array-like

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

Comments

0

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)
}

Comments

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.