Search code examples
reactjsreact-map-gl

react-map-gl library not rendering all maps


I'm using react-map-gl library to plot maps in React. I have an array of objects that I use to display a list of cards, something like this:

<div>
  {properties.map((property) => ( 
    <PropertyCard key={property.id} property={property} />
  ))}
</div>

When clicking on the card, a dialog opens displaying the map with the object's coordinates, something like this:

export const PropertyCard = ({property}:{property: PropertyInterface}) => {
    const [showMap, setShowMap] = useState(false);

    return (
        <>
            <div>{property.name}</div>
            <div>{property.address}</div>

            <button onClick={() => setShowMap(true)}>Show on map</button>

            <Dialog open={showMap} onClose={() => setShowMap(false)}>
                <Mapbox coordinates={property.coordinates} />
            </Dialog>
        </>
    );
};

The problem is that when there are many cards, the map only appears on some of them, the others are blank. I already tested the coordinates on the geojson.io website and all the coordinates worked there.


Solution

  • I had a similar problem, there is a limit on the amount of maps that can be rendered, and each PropertyCard renders a different map.

    You can remove the Dialog from the PropertyCard and add it to the parent container, that way only one map is rendered. You just need to store the coordinates in a state to display it on the map.

    Here is an example of what the code would look like.

    • The parent container:
    export const Container = () => {
      const [showMap, setShowMap] = useState(false);
      const [coordinates, setCoordinates] = useState(null);
    
      return (
        <div>
          {properties.map((property) => (
            <PropertyCard 
              key={property.id} 
              property={property}
              setShowMap={setShowMap}
              setCoordinates={setCoordinates}
            />
          ))}
    
          <Dialog open={showMap} onClose={() => setShowMap(false)}>
            <Mapbox coordinates={coordinates} />
          </Dialog>
        </div>
        );
    };
    
    • The PropertyCard:
    type TPropertyCard = {
      property: PropertyInterface;
      setShowMap: (value: boolean) => void;
      setCoordinates: (value: any) => void;
    };
    
    export const PropertyCard = ({ property, setShowMap, setCoordinates }: TPropertyCard) => {
      return (
        <div>
          <div>{property.name}</div>
          <div>{property.address}</div>
    
          <button
            onClick={() => {
              setCoordinates(property.coordinates);
              setShowMap(true);
            }}
          >
            Show on map
          </button>
        </div>
      );
    };