'close popup react-leaflet after user click on button in popup

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.



Solution 1:[1]

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!

Solution 2:[2]

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...

Solution 3:[3]

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.

Solution 4:[4]

I found the working solution for react-leaflet v3 by modifying these two links codesandbox https://codesandbox.io/s/4ws0i and https://stackoverflow.com/a/67750291/8339172

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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Luca Di Liello
Solution 2 injecteer
Solution 3 Kevin Smith
Solution 4