Search code examples
javascriptleafletreact-leaflet

React-Leaflet Tooltips are hidden behind other layer despite higher z-index


That is a follow-up question on React-Leaflet How to show tooltips above layer when using panes.

When I add a circle, the tooltip of the rectangle is hidden behind the circle, even though the z-Index of the tooltip is higher. This is confusing me, why does this happen?

const Map = (props) => {
  return (
    <MapContainer center={[48, 11]} zoom={8} id="mapId">
      <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <Pane name="rectanglePane" style={{ zIndex: 401 }}>
        <Rectangle
          bounds={[
            [47.5, 10.5],
            [48.5, 11.5]
          ]}
        >
          <Pane name="ttPane" style={{ zIndex: 403 }}>
            <Tooltip sticky>Rectangle Tooltip</Tooltip>
          </Pane>
        </Rectangle>
      </Pane>
      <Pane name="circlePane" style={{ zIndex: 402 }}>
        <Circle
          center={[48, 11]}
          radius={20000}
        >
          <Pane name="ttCirclePane" style={{ zIndex: 404 }}>
            <Tooltip sticky>Circle Tooltip</Tooltip>
          </Pane>
        </Circle>
      </Pane>
    </MapContainer>
  );
};

Map


Solution

  • The reason for this behaviour is caused by the fact that a child element's z-index is limited by the parent element's z-index. So because <Pane name="rectanglePane" style={{ zIndex: 401 }}> has a lower z-index than <Pane name="circlePane" style={{ zIndex: 402 }}>, all elements inside rectanglePane will always appear behind circlePane no matter what their z-index is.

    To get your application to work the way you want it, you will have to add the ttPane element inside another element that is outside of <Pane name="rectanglePane" style={{ zIndex: 401 }}> and one that has a higher z-index than circlePane. You will then have to work through the logistics of triggering that element which is out of the scope of this question.

    I have noticed that you are likely using components imported from another library. If that is the case and you can't add the tooltip outside of the rectanglePane element, you can try to dynamically control the zIndexes inside state and switching their values between rectanglePane and circlePane (which will switch the circle/border appearance order) . This will also involve adding your own logic, but it is unfortunately the only other way of achieving your desired result.