'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;
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quentin |
