Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot map through array of files/images React

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;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading