React-Leaflet: How to listen to LayersControl.Overlay checkbox click events?

Viewed 1863

I'm dynamically rendering some overlay controls and wanting to bind a click event listener to the checkbox of each control. However there does not currently seem to be a way to provide a React ref to LayersControl or an onClick handler to LayersControl.Overlay. Is there a better approach to achieving this functionality?

Example:

<LayersControl>
  {overlays.map(el => (
    <LayersControl.Overlay
      checked={el.checked}
      key={el.id}
      name={el.label}
    >
      <GeoJsonLayer {...el} />
    </LayersControl.Overlay>
  ))}
</LayersControl>
1 Answers

Use a ref to get the map instance and following listen to a baselayerchange event. Then using the name of your layer or the url you can implement the behavior you want.

const mapRef = useRef();

  useEffect(() => {
    const map = mapRef.current.leafletElement;
    map.on("baselayerchange", e => {
      //do whatever
      console.log(e.name);
      switch (e.name) {
        case "OpenStreetMap.Mapnik":
          flyToParis(map);
          break;
        case "OpenStreetMap.BlackAndWhite":
          console.log("do something else");
          break;
        default:
          return;
      }
    });
  }, []);

  const flyToParis = map => {
    console.log(map);
    map.panTo([48.864716, 2.349014]);
  };

Demo

Related