Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
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 Respuestas
Responde la pregunta

0

Fix code as below

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

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda