1

I am using react-leaflet and leaflet.markercluster to create custom MarkerCluster component. The idea is to pass Markers as children to MarkerCluster component. Markers are React components as well. I want to update my markers dynamically, meaning that some will be removed and added to/from array of Markers and rendered as children. LocationMarkers is an array of JSX.Elements

<MarkerCluster maxClusterRadius={100} showCoverageOnHover={false}>
  {locationMarkers}
</MarkerCluster>

Removing marker removes it visually from map until I re-add it. After that two markers appear instead of one. Cluster icon also shows wrong count, never decreasing, always increasing. Is that expected behavior with code provided? I tried to clear layers and create markers using new L.Marker() after each update and it worked, but I want to stay with Markers rendering in Map component and passing them between MarkerCluster tags as children.

import { PropsWithChildren } from "react";

import "leaflet.markercluster";
import L, { MarkerClusterGroupOptions } from "leaflet";

type MarkerClusterProps = PropsWithChildren<MarkerClusterGroupOptions>;


const createMarkerCluster = ({ children, ...props }: MarkerClusterProps, context: LeafletContextInterface) => {
  const instance = new L.MarkerClusterGroup(props);
  return { instance, context: { ...context, layerContainer: instance } }
}

const updateMarkerCluster = (instance: L.MarkerClusterGroup, props: MarkerClusterProps, prevProps: MarkerClusterProps) => {
  if (prevProps.children !== props.children) {
    // What should go here?
  }


}

const MarkerCluster = createPathComponent(createMarkerCluster, updateMarkerCluster);

export default MarkerCluster;

P.S. I've seen solutions like providig unique key to MarkerCluster component on each render so it gets re-rendered completely, but that makes all map blink for a moment and I guess it is not the best way for performance.

Andyally
  • 863
  • 1
  • 9
  • 22
  • 1
    What is the reason for not using react-leaflet-markercluster directly? – ghybs Oct 03 '21 at 03:53
  • It has same issues. Source code don't even have update function, only creation. No event unsubscruption. That causes memory leak. Maybe something changed, but last version I used had same behavior of not updating markers count in cluster, showing additional spider legs without markers – Andyally Oct 03 '21 at 11:59

0 Answers0