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

118
Views
Onclick function not defined after appending in React

I am currently getting data from an external API, and the data is formatted and styled with 3 buttons each. I then want an onclick function on all of the buttons, but when i use onclick="myFunction()", it prints function is not defined in the console.

import * as React from 'react';
function StagePage () {

function myFunction() {
console.log("test");
}

function apiCall() {
    fetch("API_URL")
        .then(response => response.json())
        .then(function (result) {
for (var i in result) {
            var match = '<div class="stage-match">'+
                '<div class="stage-kampe-odds">'+
                    '<button class="stage-kampe-odds-btn" onclick="myFunction()">Btn1</button>'+
                    '<button class="stage-kampe-odds-btn" onclick="myFunction()">Btn2</button>'+
                '</div>'+
            '</div>';

            document.getElementById("main-container").insertAdjacentHTML("afterbegin", match);
            }
        })
        .catch(error => console.log('error', error));
}
apiCall();

return (
<>
<div className="container" id="main-container"></div>
</>
)}
export default StagePage;
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

myFunction is scoped to the module, but the onclick attribute is evaluated outside of that scope.

Don't use DOM to inject HTML into your div.

Instead, put your data in the React State, and read from the state when generating your JSX.

You'll need to move the call to apiCall inside a useEffect hook to stop recursive re-renders.

There's a React + Ajax tutorial on the React website (although it uses a class component rather than a function component) which covers this.

about 4 years ago · Santiago Gelvez 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!