Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda