Search code examples
javascripttypescriptleafletreact-leaflet

Updating callbacks in leaflet-contextmenu


Problem

I am using leaflet-contextmenu v1.4.0 in react-leaflet v3.2.1. The problem is with my code below is that showColor never updates when color changes.

For example, if color is 'blue' at app initialization, showColor will know color is 'blue'. If color changes to 'red', showColor never updates; it seems to be immutable.

Question

How can I update callbacks within leaflet-contextmenu menu items?

const Component = ({ color: string }) => {
  var map = L.map('map', {
    contextmenu: true,
    contextmenuWidth: 140,
    contextmenuItems: [
      {
        text: 'Show color',
        callback: showColor,
      },
    ],
  });
  
  function showColor() {
    alert(color);
  }
};


Solution

  • I think you can only instantiate the map once, not on every re-render. Instead, just add the context menu item on each re-render.

    // Only invoke L.map() once
    var map = L.map('map', {
        contextmenu: true,
        contextmenuWidth: 140,
    });
    
    const Component = ({ color: string }) => {
    
        // update context menu items anytime color changes
        useEffect(() => {
            map.contextmenu.removeAllItems();
            map.contextmenu.addItem({
              text: 'Show color',
              callback: () => { alert(color) },
            });
        }, [color]);
    };