Search code examples
javascriptreactjsleafletreact-leaflet

react-leaflet create a custom components


I would like to create a custom component with react-leaflet that shows the actual position (x,y) of the mouse, but I don't know how to create it. I found react-leaflet-control but it seems that it is not up to date, of course I readded the api documentation https://react-leaflet.js.org/docs/en/custom-components.html but I did not understand it :/

Can someone give me an exemple of a custom component please, juste a component that display "Hello world" whould be more than enought.


Solution

  • As per documentation, to create a custom component the following steps are required:

    1)extend one of the abstract classes provided by React-Leaflet, for example:

    class MapInfo extends MapControl {
       //...
    } 
    

    2)implement createLeafletElement (props: Object): Object method to create the relevant Leaflet element instance, for example:

    createLeafletElement(opts) {
        const MapInfo = L.Control.extend({
          onAdd: (map) => {
            this.panelDiv = L.DomUtil.create('div', 'info');
            return this.panelDiv;
          }
        });
        return new MapInfo({ position: 'bottomleft' });
    }
    

    3) wrap your custom component using the withLeaflet() HOC, for example:

    export default withLeaflet(MapInfo);
    

    The following example demonstrates how create a custom component to display the actual position (lat,lng) of the mouse on map:

    Demo