Display dynamic multiple image if only present

Viewed 31

My backend API have mulitple file upload. User can have choice to upload one image or multiple or none. So, image array may be length 0, 1 or more.

Scenerio:

endpoint api/v1/img/1 may have gallery img1, img2, img3

endpoint api/v1/img/2 may have gallery img1

endpoint api/v1/img/3 may have gallery null

{ gallery.img_urls?.map((img, i) => (
   <div key={i}>
    <img src={img} alt="gallery" />
  </div>
))}

It is displaying mulitiple image. But if image isn't present it raise an error ref3.map is not a function

1 Answers

if don't want anything when no image or any error to render image then you can use

{ gallery.img_urls?.map((img, i) => (
   <div key={i}>
    <img src={img} alt="gallery" onerror="this.onerror=null; this.remove()" />
  </div>
))}


OR you can set the default image src value or also if you don't want the default image then add simply null value in src.


{ gallery.img_urls?.map((img, i) => (
   <div key={i}>
    <img src={img} alt="gallery" onerror="this.onerror=null; this.src='Default.jpg'" />
  </div>
))}

Related