Getting an error that images is null while trying to show a preview of the uploaded images in react js

Viewed 681

I have this function to upload multiple images and it works, now I need to show preview of all the images the user has selected. I tried using map and forEach to try to loop through and show the images but it isn't working. console.log(images) is showing the url of uploaded images, but images.map() or images.ForEach is throwing a null error. Can anyone tell me what's wrong in this? I am new to react, so need some help.

This is the code:

const fileObj = [];
const imageArray = [];
const [images, setImages] = useState(null); 

const uploadMultipleFiles = (e) => {
    if (e.target.name === 'images') {
        fileObj.push(e.target.files)
        for (let i = 0; i < fileObj[0].length; i++) {
            imageArray.push(URL.createObjectURL(fileObj[0][i]))
            // console.log(imageArray)
        }
        setImages({ images: imageArray })
    }
}

{console.log(images)}
<div className="form-group multi-preview">
  { {(imageArray || []).map(url => (
         <img src={url} alt="" />
      ))} 
  }
</div>
                    
 <label htmlFor="images">
      <input
         accept="image/*"
         className={classes.input}
         id="images"
         onChange={uploadMultipleFiles}
         name="images"
         type="file"
         multiple
         ref={register({required:true})}
     />
     Images
     <IconButton color="primary" component="span">
         <PhotoCamera style={{fontSize:"xx-large"}} />
     </IconButton>
  </label>
2 Answers

With your setImages({ images: imageArray }) call, you'll get value of images const to be:

images = {images: [...]} // [...] is the imageArray

so you'll have to access it as images.images, or rather set it as setImages(imageArray) which will be accessible as you expect.

Also, access the state variable and use map instead of forEach, not the imageArray. So instead of imageArray.forEach(...) use images.map(...). Map returns an array with values returned from the function calls. Whereas forEach returns undefined.

{imageArray.length>0 ? 
<div>
  {imageArray.map((element)=>{
  return(
    <img src={element} alt="" />
    )
  })}
</div>
:null}

Hope this solves

Related