3

I try to remove selection of the layer when using a mouse click on new area. Selecting an area

So there is on lick functionality on the layer

  layer.on({
    click: (event) => {
      event.target.setStyle({
        color: "black",
        weight: 1.5,
      });
    },
  });

And when I click on new area, I just get 2 areas with such border, but need only to select new one, and remove previous. Can anybody help with that?

enter image description here

Here is the code how I use geoJSON

<MapContainer center={getCenter()} zoom={getZoom()}>
    <GeoJSON
        ref={geoJSON}
        center={getCenter()}
        zoom={getZoom()}
        style={setColor}
        data={germanyDis}
        onEachFeature={onEachArea}
    />
</MapContainer>

And here is my onEachArea function

const onEachArea = (area, layer) => {
      layer.on({
        click: (event) => {
          event.target.setStyle({
            color: "black",
            weight: 1.5,
          });
          event.target.bringToFront();
   
        },
      });
Roman
  • 83
  • 7

2 Answers2

2

So fixed this issues. Created a usePrevious hook to store previous target value and used it in useEffect hook

 const [selectedFeature, setSelectedFeature] = useState(null);
 const previousFeature = usePrevious(selectedFeature);

  useEffect(() => {
    if (previousFeature) {
      previousFeature.setStyle({ color: "transparent", weight: 0 });
    }
  }, [selectedFeature]);

And in onEachFeature function just set current value

const onEachArea = (area, layer) => {
      layer.on({
        click: (event) => {
          event.target.setStyle({
            color: "black",
            weight: 1.5,
          });
          event.target.bringToFront();

          setSelectedFeature(event.target);

        },
      });
    }
  };
Roman
  • 83
  • 7
1

When you add the layers via L.geoJson and with the style function, you can simply call on the geojson group geojsonGroup.resetStyle() in the click event:

layer.on({
    click: (event) => {
      geojsonGroup.resetStyle()
      event.target.setStyle({
        color: "black",
        weight: 1.5,
      });
    },
  });
Falke Design
  • 10,635
  • 3
  • 15
  • 30