react-leaflet manage close popup on Child Component

25 Views Asked by At

I'm trying to make a react-leaflet popup everytime I click a link that changes the marker position in the child component, but it never closes de popup, here's what it looks like on the map component


  const markerRef = useRef();

const handleClosePopup = () => {
    console.log("Closing popup");
    if (markerRef.current && markerRef.current.leafletElement) {
      markerRef.current.leafletElement.closePopup();
    }
  };

return (
<MapContainer
          center={center}
          ref={mapRef}
          zoom={4}
          scrollWheelZoom={false}
          dragging={true}
          zoomControl={false}
        >
          <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
          <Marker position={marker} ref={markerRef}>
            <Popup closeOnClick={false}>
              <Modal />
            </Popup>
          </Marker>
        </MapContainer>
        <div className={`sidebar ${sidebarOpen ? "show" : ""}`}>
          <div className="list">List</div>
          {
            <ChildComponent
              setMapViewPosition={setMapViewPosition}
              handleClosePopup={handleClosePopup}
            />
)

and here is what the child component looks like

function ChildComponent({ setMapViewPosition, handleClosePopup }) {
return (
    <>
      <ul>
        {list.map((item, index) => (
          <li key={index}>
            <Link
              to={`/api/people/${item.names}`}
              onClick={() => {
                setMapViewPosition([item.X, item.Y]);
                handleClosePopup(); 
              }}
            >
              {item.name}
            </Link>
          </li>
        ))}
      </ul>
}

I expect that everytime that I click on a link, the popup closes and the marker position changes, I have troubles with the popup closing part.

0

There are 0 best solutions below