Friday 13 November 2020

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

Hey guys 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. Thanks

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= />
     </IconButton>
  </label>


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

No comments:

Post a Comment