Search code examples
reactjsreact-leaflet

`leafletElement` is getting undefined in react-leaflet


When I try the below code-sandbox link in my project. I'm facing issue like leafletElement is getting undefined.

Below are the versions :-

"react-leaflet": "^3.1.0", "react-leaflet-enhanced-marker": "^1.0.21",

https://codesandbox.io/s/relaxed-kepler-9sw2n?file=/src/App.js


Solution

  • Your code needs several adjustments:

    1. now zoom and center are immutable meaning you cannot change them via setState. You need to hold the mapReference as state variable to achive that.
    2. leafletElement is deprecated when deriving the marker reference
    3. openPopup does not expect any args. This comes from the leaflet API and not from react-leaflet

    Your code should look like this:

        this.state = {
             ...
              map: null,
              marker: null
            };
    
        openPopUp = (marker, id) => {
            console.log(marker);
            if (marker) marker.openPopup();
          };
        
          clickAction = (id, lat, lng) => {
            if (!this.state.map) return;
            this.state.map.setView([lat, lng], 16);
            this.markerRefs[id].openPopup();
          };
        
          render() {
            return (
              <>
                <MapContainer
                  center={center}
                  zoom={zoom}
                  whenCreated={(map) => this.setState({ map })}
                >
               ...
            )
          }
     }
    

    Demo