Search code examples
reactjsleaflet

How do I Import Plugins into Leaflet React App


I am trying to import leaflet plugins into a React App where I also have Leaflet.js. I have added leaflet and the plugin script tags and links to the head tag -- but I am not sure how to call or use the plugin the react page / component.

Kindly note that I am not using react-leaflet --- although if I may import plugins easily using that, I would be happy to consider.

<script src="%PUBLIC_URL%/leaflet/leaflet.js"></script>
<script src="%PUBLIC_URL%/pan.js"></script>

The github plugin may be found here : ( I just extracted the js file, renamed to pan.js and put in the head tag) and I can see it succesfully imported using a Get 200 in my network dev tools.

https://github.com/kartena/Leaflet.Pancontrol/

When called in script `L.control.pan()` does not work in React.

I wish to use a number of plugins-- is there an approach in general? I see several specific answers, but am a loss for a general approach as to have to integrate and then use these plugins.

Ideally, not involving a full rewrite of the plugin.


Solution

  • You need tο install the plugin using npm or yarn and import their relavant files (js or css).

    In this particular case to install Leaflet.Pancontrol you first install the plugin:

    npm i leaflet.pancontrol 
    

    but if you check the official page this plugin has the requirement to install and use also leaflet-tilejson. It does not mention that but you can see it inside the folder examples where it imports leaflet-tilejson and proj4leaflet So install them also:

    npm i leaflet-tilejson
    npm i proj4leaflet
    

    After you install these plugins you need to import them like es6 modules. If they are exported also like es6 modules you can import them directly but in this case you need to import the entire objects plus the css file.

    import * as TileJSON from "leaflet-tilejson";
    import "leaflet.pancontrol/src/L.Control.Pan.css";
    import * as PanControl from "leaflet.pancontrol/src/L.Control.Pan.js"
    

    And then instead of calling L.plugin you can use them like this:

    useEffect(() => {
        const map = TileJSON.createMap("map", osmTileJSON, {
          mapConfig: { zoomControl: false }
        });
    
        new PanControl.default().addTo(map); // instead of  L.control.pan().addTo(map);
        new PanControl.Zoom().addTo(map); // instead of         L.control.zoom().addTo(map);
    
      }, []);
    

    Demo

    And you get the same result as in this vanilla js demo