Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

98
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda