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

173
Views
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 answers
Answer question

0

Fix code as below

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

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 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!