Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

120
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda