Trees4theForest
Trees4theForest

Reputation: 1386

React Leaflet Change Color of GeoJSON Feature on Hover

Can't seem to find a simple way to change the color of a feature when I hover over it.

Using react-leaflet wigh GeoJSON:

export default function BaseMap({ places }) {
  
  return (
    <MapContainer
      scrollWheelZoom={true}
      preferCanvas={true}
      renderer={bufferedRenderer}
    >

      {features.map((feature) => {

        const trailName = feature.properties.TRAIL_NAME_LOWER || "Trail Name";

        return (
          <GeoJSON key={feature.properties.fid} data={feature}>
            <Popup>
              <PopupInfo
                name={trailName}
                distance={feature.properties.TRAIL_LENGTH}
                id={feature.properties.fid}
              />
            </Popup>
            <Tooltip>{trailName}</Tooltip>
          </GeoJSON>
        );
      })}
      <LocationMarker />
    </MapContainer>
  );
}

Is there a simple way to say:

onHover: style

Upvotes: 0

Views: 883

Answers (1)

dup.titung
dup.titung

Reputation: 450

You will need to use onEachFeature function and then change the fillColor of the layer on mouseover

<GeoJSON 
    onEachFeature={(feature, layer) => {
      layer.on({
        mouseover: (e) => {
          e.target.setStyle({ fillColor: 'red' });
        },
      });
    }}
>
......
</GeoJSON>

Also, don't forget to add a mouseout event handler to revert back to previous color.

Upvotes: 1

Related Questions