React Leaflet - Dynamically load popup content

Viewed 529

I am using React Leaflet for map implementation. How can we load popup content dynamically ? The dynamic contents are getting from an api.

i tried using state change (for popup content) in the component .

Map component as follows:

import React from 'react'
import { Map, Marker, Popup, TileLayer, Circle, Tooltip } from 'react-leaflet'
import 'leaflet/dist/leaflet.css';
import orangeIcon from '../../../../assets/images/mapmarkers/marker-icon-orange.png';
import shadwoIcon from '../../../../assets/images/mapmarkers/marker-shadow.png';


const CustomerViewOnMap = React.memo((props) => {
  const tileLayerUrl = `https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`;
  const defaultZoomValue = 11;
  const [currentZoomValue, setCurrentZoomValue] = React.useState(defaultZoomValue);
  const position = props.originData ? props.originData.position : [];
  const nearByMarkerDefaultProperties = { iconUrl: orangeIcon, shadowUrl: shadwoIcon, iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], shadowSize: [41, 41] };
  const [currentMarkerData, setCurrentMarkerData] = React.useState();

  React.useEffect(() => {
    const L = require("leaflet");
  }, []);

  const openPopup=(e,markerItem)=>{
    setCurrentMarkerData(<div>Test Data</div>)
  }

  return (
    <>
      <div className="customer-map-wrap">
        {
            <Map center={position} zoom={defaultZoomValue} onZoomEnd={(e) => zoomlevelschange(e)}>
              <TileLayer url={tileLayerUrl} />
              {
                props.mapData.map((map, index) => {
                  return <Marker key={index} position={map.position} icon={nearByMarkerDefaultProperties} onOpen={(e)=>openPopup(e,map)} >
                    <Popup key={props.refreshKey} className="customer-popup" >{currentMarkerData}</Popup>
                    {
                      currentZoomValue < 5 && <Tooltip direction='top' offset={[0, -41]} opacity={1} permanent><span>{map.customer_name}</span></Tooltip>
                    }
                  </Marker>;
                })
              }
            </Map>
        }
      </div>
    </>
  );

});
export default CustomerViewOnMap;
0 Answers
Related