Home > Enterprise >  Render img element for each of the IDs in multiple arrays
Render img element for each of the IDs in multiple arrays

Time:12-14

I'm getting the image IDs for gallery photos from reddit in this way:

// Check if post is a gallery and if yes, map through each image and get the id
if (post.is_gallery) {
  const id = post.gallery_data.items.map((item) => item.media_id);
  console.log(id);
}

I want to put each of these IDs in an <img /> element and render them, but the response I get from that if statement is like this:

enter image description here

How can I get each of those IDs from their arrays and render them in multiple <img > elements?

<img
  src={`https://i.redd.it/${id-goes-here}.jpg`}
  className="image"
  alt="Gallery Images"
/>

CodePudding user response:

You can map over your data and return an img tag like this:

const images = post.gallery_data.items.map((item) => <img src={`https://i.redd.it/${item.media_id}.jpg`} 
                                                          key={item.media_id} 
                                                          className="image" 
                                                          alt="Gallery Images"/>);

then you can put your images variable in your jsx, like this:

return (<>{images}</>)

Aslo you can put the map directly in your jsx rendering, like this:

  return (<>{post.gallery_data.items.map((item) => <img src={`https://i.redd.it/${item.media_id}.jpg`} 
                                                        key={item.media_id} 
                                                        className="image" 
                                                        alt="Gallery Images"/>
              }</>);
  • Related