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

97
Views
Functional component event is still active when state is toggled - REACT MAPBOX

I'm trying to build an app where you can toggle effects by clicking on the navitems.

On the nav items I have an event listener that toggles state

const [marker, setMarker] = useState(false);

onClick={() => setMarker(!marker)}

The idea is when it's set to true, you can click on the map to set a waypoint. And when it's false, clicking does the default behavior.

I tried using an if statement like this

    if (marker) {
      map.current.on('click', (e) => {
        new mapboxgl.Marker().setLngLat(e.lngLat).addTo(map.current);
        // Create a new marker.
      });
    }

Whether state is true or false, you can still place a waypoint after toggling it for the first time.

Can someone please tell me what I'm missing here? I know it's something stupid.

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

0

I've faced the same problem when I began to use React Hooks! Don't worry, that's because you have no code for removing the added click event for map Ref! So you just need to cleanup the click event for the map object!

useEffect(() => {
    function clickHandler(e) {
        new mapboxgl.Marker().setLngLat(e.lngLat).addTo(map.current);
        // Create a new marker.
    }
    if (marker) {
        map.current.on('click', (e) => {
            clickHandler(e)
        });
    }
    return () => {
        map.current.removeEventListener('click', clickHandler)
    }
}, [marker]);

Please try this way.. Good luck..

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!