Home > front end >  Image not displayed in React via an API
Image not displayed in React via an API

Time:10-29

I have a component that is displaying an API fine but when I try to add an image via a different API I get an error but not sure what to look for as most examples are similar but for some reason I cannot get the Image to display

Image component

import React, { useState, useEffect } from "react";

const imgURL =
  "https://rl-uk2.azureedge.net/picturemanager/images/OBMNG1/hotel4.jpg";

const HotelImage = () => {
  const [image, setImage] = useState();

  const fetchImage = async () => {
    const res = await fetch(imgURL);
    const imageBlob = await res.blob();
    const imageObjectURL = URL.createObjectURL(imageBlob);
    setImage(imageObjectURL);
  };

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

  return (
    <div>
      {image.map((data) => {
        return (
          <div className="list-group-item hotel-area" key={data.id}>
            <div>{data.images}</div>
          </div>
        );
      })}
    </div>
  );
};

export default HotelImage;

And I want it to be called here in a different component:

return (
    <div>
      {hotel.map((data) => {
        return (
          <div className="list-group-item hotel-area" key={data.id}>
            <div>{data.name}</div>
            <div>
              <Image />
            </div>
            <div>{data.address1}</div>
            <div>{data.address2}</div>
            <div className="star-rating">{data.starRating}</div>
          </div>
        );
      })}
    </div>
  );

The images API endpoint looks to be like this:

"images":[{"url":"https://rl-uk2.azureedge.net/picturemanager/images/OBMNG1/Hotel1.JPG"},{"url":"https://rl-uk2.azureedge.net/picturemanager/images/OBMNG1/hotel4.jpg"}

CodePudding user response:

Using img tag is a better option

const example = () => {
  return (
    <div>
      {hotel.map((data) => {
        return (
          <div className="list-group-item hotel-area" key={data.id}>
            <div>{data.name}</div>
            {/* List the images */}
            {data.images.map((image) => (
              <img src={image.url}></img>
            ))}
            <div>{data.address1}</div>
            <div>{data.address2}</div>
            <div className="star-rating">{data.starRating}</div>
          </div>
        );
      })}
    </div>
  );
};
  • Related