So basically want to make custom close for react-leaflet Popup component, seams that is not a big problem to do with native API leaflet but with react component from react-leaflet I can't find the solution.
at the moment, the only way I found to close the popup is the following:
constructor(props){
super(props);
this.popup = React.createRef();
}
// the magic
closePopusOnClick(){
this.popup.current.leafletElement.options.leaflet.map.closePopup();
}
render(){
return <Marker position={[this.props.lat, this.props.lng]}>
<Popup ref={this.popup}>
<Button onClick={this.closePopusOnClick}>Close popup</Button>
</Popup>
</Marker>;
}
Hope it helps!
In "react-leaflet": "^3.0.2"
I managed to close the popup with:
popupRef.current._closeButton.click()
Not very nice comparing to a future Popup.close()
method which MUST work out-of-box, but gets the job done...
I ended up with a similar solution to Luca's Answer, so I thought I'd add it as an answer too. I needed to close all popups when moving or zooming the map and ended up with the following:
import React, { useRef } from "react";
import { Map } from "react-leaflet"
export default () => {
const mapRef = useRef(null);
const closePopups = () => {
mapRef.current.leafletElement.closePopup();
};
const handleOnDragend = e => {
closePopups();
};
const handleOnZoomend = e => {
closePopups();
};
if (typeof window === 'undefined') {
return null;
}
return (
<Map
ref={mapRef}
onDragend={handleOnDragend}
onZoomend={handleOnZoomend}
>
</Map>
)
}
This can, however, be extended so that anything can call the closePopups
method.
I found the working solution for react-leaflet
v3 by modifying these two links codesandbox https://codesandbox.io/s/4ws0i and https://mcmap.net/q/1774849/-react-leaflet-close-popup-on-button-click
here is the function to hide the Popup
component
const hideElement = () => {
if (!popupElRef.current || !map) return;
map.closePopup();
};
here is the Popup
component
<Popup ref={popupElRef} closeButton={false}>
<button onClick={hideElement}>Close popup</button>
</Popup>
In the latest react-leaflet
Map
simply has a closePopup()
method. Here is a working example with MapContainer
.
const [map, setMap] = useState<Map|null>(null);
return (
<MapContainer ref={setMap} center={[44,44]} zoom={7}>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={[44,44]}>
<Popup>
<button
onClick={() => {
map && map.closePopup();
}}
>
Close me!
</button>
</Popup>
</Marker>
</MapContainer>
);
© 2022 - 2024 — McMap. All rights reserved.