0

I want to set the layer order of my react leaflet map by calling bringToBack() on my selected layer after the component has rendered.

I tried getting the layer with useRef() and then calling bringToBack() in my useEffect Call.

const LayerSupplies = () => {
    const supplies = useSelector((state) => state.map.supplies);
  const supplyLayer = useRef();
  useEffect(() => {
    if(supplyLayer.current !== undefined){
        supplyLayer.current._layers[Object.keys(supplyLayer.current._layers)[0]].bringToBack();
    }
  })

    if (supplies.length > 0) {
      return (
        <LayersControl.Overlay
          name="Supply"
        >
          <LayerGroup
            ref={supplyLayer}
          >
            {supplies.map((supply) => (
              <Polygon
                pathOptions={
                    {
                        fillColor: "#707070",
                        color: "#3F4144",
                        fillOpacity: 0.6,
                        weight: 1.3,
                    } }
                key={supply.id}
                positions={supply.footprint}
              >
              </Polygon>
            ))}
          </LayerGroup>
        </LayersControl.Overlay>
      );
    }
  }

The supplyLayer component will then be called in my <MapContainer/> among other similar components.

1 Answers1

0

This approach actually works, my problem was that I didn't update my state correctly so the useEffect didn't run. It's also better to loop over the layers and bring each to front like this:

useEffect(() => {
    if(supplyLayer.current !== undefined) {
              Object.entries(supplyLayer.current._layers).forEach((layer) => layer[1].bringToFront()); 
            }