Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
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);
  }
};

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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]);
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!