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

175
Visualizações
How to define a button and a function inside js (React)
  • I am using MapBox to render a map. I have made a onClick function wherein when clicked on the map it shows the geocode information shown in the screenshot below through api.

enter image description here

  • Now what I want is to have a button below the table and when click on it I want it to execute a particular function, I have defined it but when clicked on it says Function is not defined
  • Code
map.current.on('click', function(e) {

        var coordinates = e.lngLat;
        var lng = coordinates.lng;
        var lat = coordinates.lat;
        console.log(lat);
        console.log(lng);
        var d = fetch("https://api.mapbox.com/geocoding/v5/mapbox.places/" + lng + "," + lat + ".json?access_token={token_value}").then(response => response.json()).then(function(data) {
          console.log(data)
          var str = "<table border='1'><tr><td><center>Title</center></td><td><center>Content</center></td></tr>"
          for (let i in data["features"]) {
            str = str + "<tr><td style='padding:5px'>" + data["features"][i]["place_type"][0] + "</td><td style='padding:5px'>" + data["features"][i]["place_name"] + "</td></tr>"

          }

          str = str + "</table>"
          
          // button
          str = str + "<button onClick={myFunction}>Save</button>"

          function myFunction() {
            console.log('Saved pressed');
          }
          
          new mapboxgl.Popup()
            .setLngLat(coordinates)
            .setHTML(str)
            .addTo(map.current)
        });
        console.log(d);
      });
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Fix code as below

// button
str += `<button onclick="myFunction()"}>Save</button>`;
about 4 years ago · Juan Pablo Isaza Relatório

0

I would guess the button (and the function name defined for it) are created with a different scope than where you have defined your function. One of these might work:

  1. Define your function as const myFunction = () => console.log("saved pressed").
  2. Try referencing your function as this.myFunction
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