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

Render img element for each of the IDs in multiple arrays

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

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

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"
/>

>Solution :

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"/>
              }</>);
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