Home > front end >  How to define a button and a function inside js (React)
How to define a button and a function inside js (React)

Time:12-30

  • 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);
      });

CodePudding user response:

Fix code as below

// button
str  = `<button onclick="myFunction()"}>Save</button>`;

CodePudding user response:

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
  • Related