How to add images to React through an API call and not importing the image?

I’m trying to use data that has an image url as part of an object. Normally, you would assign import the image and assign it to a variable. However, I am unable to do that as I’m planning on using an API call to get this image urls. Currently I’m using mock data and have been unable to successfully render the image. I want to add an image to the <InfoWindow> component.

I’ve tried:

 <img src={selectedSite.image} alt={`alien ${selectedSite.eventType}`} />
 <img src={require(`${selectedSite.image}`} alt={`alien ${selectedSite.eventType}`} />

Mock Data

export const mockSightings = [
  {
    name: '',
    lat: '47.7511',
    lng: '-120.7401',
    description: 'BIG BLUE BALL IN SKY OMG',
    eventType: 'sighting',
    image: 'https://cdn.mos.cms.futurecdn.net/QkuLCPzH7GUVS9MthdWM9M.jpg',
  },
  {
    name: 'Billy Bob',
    lat: '43.8041',
    lng: '-120.5542',
    description: 'BIG RED BALL IN SKY OMG',
    eventType: 'sighting',
    image: 'https://ewscripps.brightspotcdn.com/dims4/default/3402aa2/2147483647/strip/true/crop/1000x563+0+0/resize/1280x720!/quality/90/?url=http%3A%2F%2Fewscripps-brightspot.s3.amazonaws.com%2F5a%2F57%2F58a3662b422a8fb6464451f244eb%2Flarge-fireball-seen-across-fl-sky-mari-g.png',
  },
  {
    name: 'Stephanie Jo',
    lat: '44.0682',
    lng: '-114.7420',
    description: 'rotating lights',
    eventType: 'sighting',
    image: 'https://i.dailymail.co.uk/i/pix/2016/10/04/01/391305FA00000578-3820675-image-a-23_1475542666609.jpg',
  }
]

Component

import React, { useState } from "react";
import {
  GoogleMap,
  useJsApiLoader,
  Marker,
  InfoWindow,
} from "@react-google-maps/api";
import { mockSightings } from "../../mockdata";

const containerStyle = {
  width: "1500px",
  height: "800px",
};

const center = {
  lat: 39.8283,
  lng: -98.5795,
};

const SightingsMap = () => {
  const [selectedCenter, setSelectedCenter] = useState(null);
  const [selectedSite, setSelectedSite] = useState(null);

  const { isLoaded } = useJsApiLoader({
    id: "google-map-script",
    googleMapsApiKey: `${process.env.REACT_APP_API_KEY}`,
  });

  const generateMarkers = () => {
    return mockSightings.map((sighting) => {
      const position = {
        lat: parseInt(sighting.lat),
        lng: parseInt(sighting.lng),
      };
      return (
        <Marker
          position={position}
          onMouseDown={() => {
            setSelectedSite(sighting);
          }}
          onMouseUp={() => {
            setSelectedCenter(position);
          }}
        />
      );
    });
  };

  return isLoaded ? (
    <GoogleMap mapContainerStyle={containerStyle} center={center} zoom={5}>

      {generateMarkers()}

      {selectedCenter && (
        <InfoWindow
          onCloseClick={() => {
            setSelectedCenter(null);
          }}
          position={selectedCenter}
        >
          <div>
            <div>
              <p>{selectedSite.name ? selectedSite.name : "anonymous"}</p>
              <p>{selectedSite.description}</p>
              <p>{selectedSite.eventType}</p>
            </div>
            <img src={selectedSite.image} alt={`alien ${selectedSite.eventType}`} />
          </div>
        </InfoWindow>
      )}
    </GoogleMap>
  ) : (
    <></>
  );
};

export default SightingsMap;

61 thoughts on “How to add images to React through an API call and not importing the image?”

Leave a Comment