Search code examples
reactjspopupmapboxmarkerreact-map-gl

Show popup for only one Marker react map gl


I'm using react-map-gl and states so that when a marker is clicked on the popupOpen is set to true and the popup shows up.

This works with maps with only one marker but when I use a map fuction to send coords of multiple markers, clicking on any of them opens all popups because the binded state cotrols them all.

How do I set it up so that only the popup related to a specific marker shows up?

// state
const [popupOpen, setPopupOpen] = useState(false);

// marker & popup

          {landmarkData.map((data, index) => (
            <div key={data._id}>
              <Marker
                key={index}
                longitude={data.longitude}
                latitude={data.latitude}
                onClick={() => setPopupOpen(true)}
              >
                <RoomIcon fontSize="small" style={{fill: "red"}} />
              </Marker>
              {popupOpen && (
                <Popup
                  key={index}
                  latitude={data.latitude}
                  longitude={data.longitude}
                  onClose={() => setPopupOpen(false)}
                  closeButton={true}
                  offsetLeft={10}
                >
                  <span style={{fontSize: "1vw", fontFamily: "Poppins"}}>
                    {data.name}
                  </span>
                </Popup>
              )}
            </div>
          ))}

Solution

  • You should individually track the popup open state; like this:

    
    // state
    const [popupOpen, setPopupOpen] = useState({});
    
    // render
    
    
              {landmarkData.map((data, index) => (
                <div key={data._id}>
                  <Marker
                    key={index}
                    longitude={data.longitude}
                    latitude={data.latitude}
                    onClick={() => setPopupOpen({...popupOpen, popupOpen[data._id]: true })}
                  >
                    <RoomIcon fontSize="small" style={{fill: "red"}} />
                  </Marker>
                  {popupOpen[data._id] && (
                    <Popup
                      key={index}
                      latitude={data.latitude}
                      longitude={data.longitude}
                      onClose={() => setPopupOpen(false)}
                      closeButton={true}
                      offsetLeft={10}
                    >
                      <span style={{fontSize: "1vw", fontFamily: "Poppins"}}>
                        {data.name}
                      </span>
                    </Popup>
                  )}
                </div>
              ))}