Home > Back-end >  Cannot display 1 image from a Array from a API
Cannot display 1 image from a Array from a API

Time:10-31

I can manage to display all and have them in roughly the right place with CSS, however in the case where there is more than 1 image, I cannot display just that first image

I eventually want to be able to click the image and display a Modal showing a gallery of these pics, but stuck on this part:

import React, { useState, useEffect } from "react";
import "./Hotel.css";

const URL = "https://obmng.dbm.guestline.net/api/hotels?collection-id=OBMNG";

const Hotel = () => {
  const [hotel, setHotel] = useState([]);

  useEffect(() => {
    hotels();
  }, []);

  const hotels = async () => {
    const response = await fetch(URL);

    setHotel(await response.json());
  };

  //   filter hotels button displayed by star rating
  const filterHotels = (e) => {
    const starRating = e.target.value;
    const filteredHotels = hotel.filter(
      (hotel) => hotel.starRating === starRating
    );
    setHotel(filteredHotels);
  };

  //   store filteredHotels in state
  const [filteredHotels, setFilteredHotels] = useState([]);

  useEffect(() => {
    setFilteredHotels(hotel);
  }, [hotel]);

  return (
    <div>
      <div className="selection-filter">
        {/* drop down for useState */}
        <label for="filter">Filter by star rating: </label>
        <select onChange={filterHotels}>
          <option value="0">All</option>
          <option value="1">1 Star</option>
          <option value="2">2 Star</option>
          <option value="3">3 Star</option>
          <option value="4">4 Star</option>
          <option value="5">5 Star</option>
        </select>
      </div>
      {hotel.map((data) => {
        return (
          <div>
            <div className="list-group-item hotel-area" key={data.id}>
              <div className="hotel-name">{data.name}</div>
              {data.images.map((image) => (
                <img
                  className="hotel-image"
                  src={data.images[0].url}
                  alt={image.alt}
                />
              ))}
              <div className="hotel-address">{data.address1}</div>
              <div className="hotel-address">{data.address2}</div>
              <div className="star-rating fas fa-star">{data.starRating}</div>
              <hr />
            </div>
          </div>
        );
      })}
    </div>
  );
};

export default Hotel;

CodePudding user response:

It displays 3 images, because the first hotel object in the response object has 3 elements in the images array. If you want to show only one (first) image, don't use .map function, just render the first image, see this example.

  • Related