Home > Net >  Onclick function not defined after appending in React
Onclick function not defined after appending in React

Time:04-13

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 >' 
                '<div >' 
                    '<button  onclick="myFunction()">Btn1</button>' 
                    '<button  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;

CodePudding user response:

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.

  • Related