React Leaflet 4.2.0 - how to change zoom on button click?

496 Views Asked by At

**I would like to add a button next to the map, after clicking which I will be able to change the zoom of the map. ** Is this feasible in the new version of react-leaflet?

Example scenario: I display a map of the country with zoom 7, above the map I have a few buttons with the names of cities, after clicking on the button, I would like to move to this place and increase the zoom to 9.

i tried using ref and looked at the documentation, in older versions it worked.

It was enough to use useState() and change the zoom value.

1

There are 1 best solutions below

0
On

Ok, i needed to use useRef() and flyTo.

const mapRef = useRef();
...

<button type="button" onClick={handleClick}> Warsaw </button>

<MapContainer center={position} zoom="7" ref={mapRef}>
...


const handleClick = () => {
  mapRef.current.flyTo([52.0121, 20.585842], 12);
};