bhagwans
bhagwans

Reputation: 163

How to add a legend to the map using react leaflet, without using refs and manually modifying the DOM?

I'm using react-leaflet and want to add a legend to the map.

I can currently do it by passing a ref of the map to a custom component and render null while having a function create the HTML and add it to the map. The refs are being a nightmare to test using Jest and Enzyme.

Is there a way to using a react-leaflet component to accomplish this?

Upvotes: 2

Views: 5254

Answers (1)

kboul
kboul

Reputation: 14570

You can achieve that by extending react-leaflet's MapControl class and using for instance the legend code provided by Leaflet official page tutorial for Using GeoJSON with Leaflet.

class Legend extends MapControl {
   componentDidMount() {
      // place your code here

      ...
      const legend = L.control({ position: "bottomright" });

      ...
      const { map } = this.props.leaflet;
      legend.addTo(map);
   }
}

and then import it here:

 <Map style={{ height: "100vh" }} center={position} zoom={13}>
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        />
        <Legend />
 </Map>

Demo

Upvotes: 9

Related Questions