Leaflet React get map instance in functional component Leaflet React get map instance in functional component reactjs reactjs

Leaflet React get map instance in functional component


You need to use a component which will include your button inside. To take the map instance use whenCreated prop of MapContainer. I think mapRef is not valid anymore with the latest version.

MapContainer:

 const [map, setMap] = useState(null); <MapContainer      center={[50, 50]}      zoom={zoom}      style={{ height: "90vh" }}      whenCreated={setMap}  >...</MapContainer><FlyToButton />  // use the button here outside of the MapContainer....

Create the component with the button and its event

function FlyToButton() {  const onClick = () => map.flyTo(regionCoord, zoom);      return <button onClick={onClick}>Add marker on click</button>;}

Demo


you need to access the map element(from the map component which is the container not MapContainer), this is a very simple example:

export default function MapComponent() {    const [mapCenter,setMapCenter] = useState([13.1538432,30.2154278])    let [zoom,setZoomLevel] = useState(15)    let [tile,setTile] = useState('https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png')        let mapRef = useRef();    const fly=()=>{        mapRef.current.leafletElement.flyTo([14,30],15)    }    return (    <>        <button onClick={fly}>Click</button>        <Map center={mapCenter} zoom={zoom} ref={mapRef} style={{width:'100%',height:'100%'}}>            <TileLayer url={tile}/>        </Map>    </>      )}