0

I want to pass the images of an array of objects into the divs of a swiper slider carousel but when I do the map into the fetch to creat the HTML of the img tag with the value of the object who holds the image it doesn't work properly, it shows all the images in the first div and the other divs who have the same class doesn't show any img of the array. I dont know what to do :S

 <!-- Swiper -->
<div class="swiper mySwiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide imgdata">Slide 1</div>
    <div class="swiper-slide imgdata">Slide 2</div>
    <div class="swiper-slide imgdata">Slide 3</div>
    <div class="swiper-slide imgdata">Slide 4</div>
  </div>
  <div class="swiper-button-next"></div>
  <div class="swiper-button-prev"></div>
</div>

<!-- Initialize Swiper and Fetch -->
<script>
  let linkApi = "https://picsum.photos/v2/list?limit=4";

  fetch(linkApi)
    .then((res) => res.json())
    .then((data) => {
      console.log(data);

      let dataimg = "";
      data.map((values) => {
        dataimg += `<img src=${values.download_url}>`;
      });
      document.querySelector(".imgdata").innerHTML = dataimg;
    })
    .catch((err) => {
      console.log(err);
    });

  let swiper = new Swiper(".mySwiper", {
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
  });
</script>

1 Answers1

0

Try replacing your code inside the second .then() with this:

let images = [];
data.forEach((value, index) => {
    images[index] = `<img src=${value.download_url}>`;
}

document.querySelectorAll(".imgdata").forEach((item, index) => {
    item.innerHTML = images[index];
}

Few things to note:

  1. I use forEach instead of map since you’re not really transforming the array, just getting a value from each item.
  2. You have to use querySelectorAll() to get all the elements with that class. You were only changing the first one since querySelector returns the first element that matches and only the first.
matronator
  • 465
  • 6
  • 13