Search code examples
reactjsleafletreact-leafletreact-leaflet-v3

When I load the map React leaflet will some open popups be initialized?


I was able to get the map reference using const map = useRef (null) but now I need to have some popup open when I start the map;

const map = useRef (null);

<MapContainer
    zoom={15}
    center={state.currentLocation}
    
    whenCreated={(mapInstance) => {
      map.current = mapInstance;
    }}
  >{listFarol.map((place) => {

  return (
    <>
      <Marker
        key={place.id}
        position={place.pos}
        icon={myIcon}
   
      >
        {place.name=== 'A' ? (
          <Popup >{place.name}</Popup >
        ) : <Popup >{place.name}</Popup >} 

      </Marker>
    </>
  );
})}
<LocationMarker position={installActive} /></MapContainer>

But in case you want to use this reference to be able to define a series of popups that I want when the app starts open, in my case those that meet the condition place.name === 'A'


Solution

  • Define a custom Marker comp which will have the popup open

    function MarkerWithOpenPopup(props) {
      const markerRef = useRef();
    
      useEffect(() => {
        if (!markerRef.current) return;
        markerRef.current.openPopup();
      }, []);
    
      return <Marker ref={markerRef} {...props} />;
    }
    

    Then create a ternary for instance to decide which marker comp will be used during the loop:

    {markers.map(({ name, id, pos }) => {
        const MarkerComp = name === "name 1" ? MarkerWithOpenPopup : Marker;
        return (
           <MarkerComp position={pos} icon={icon} key={id}>
             <Popup>{name}</Popup>
           </MarkerComp>
        );
    })}
    

    You can even improve this by providing a flag on the markers array and not checking the popup name explicitly

    Here is a simplified demo