How can I access the map object since the whenCreated prop was removed in react-leaflet v4.x?

75 Views Asked by At

I have been struggling with an issue which comes down to me not being able to properly reference the map object. After researching it for a few days, I've come to the conclusion that the "old" (up to v3.x) whenCreated prop of the MapContainer, which returned the Leaflet.Map object, has been removed.

Now all that's left is the whenReady prop, which is defined as () => void. Therefore I am struggling to access the map object, which I desperately need.

Does anyone have any tips for this?

1

There are 1 best solutions below

0
On

The release notes for React Leaflet v4 state:

Removed whenCreated property from the MapContainer component (a ref callback can be used instead).

What you can do is define a state to store a reference to the map:

const [map, setMap] = useState(null);

then when you create your MapContainer get a reference to the map:

<MapContainer
  center={[52.4498, -1.6]}
  zoom={12}
  scrollWheelZoom={false}
  ref={setMap}
>
  <TileLayer
    attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
  />
</MapContainer>

then define a useEffect where you can access the map object:

useEffect(() => {
  if (map) {
    map.on('click', (e) => {
      map.setZoom(8);
    });
  }
}, [map]);

There's a StackBlitz here to demonstrate this. If you click anywhere on the map, the code above will execute and set the zoom level to 8.