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

116
Vistas
Alert is getting triggered automatically in react

I am new to reactjs, I have been trying to design a UI such that o every click it displays alert telling this li element is clicked but when the page is rendered I see lot of alerts getting popped out. Can someone point out mistake in my code and how to avoid it!

Here is the code snippet

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <!-- <meta name="theme-color" content="#000000" /> -->
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <title>Grade Score</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

App.js

import './App.css';

function clickhandle (props) {
  alert("you clicked on" + props.name)
}

function Stud(props) {
  return <li onClick={clickhandle(props)}> { props.name }</li>;
  
}

function App() {
  const students = ['Anil', 'Bob' , 'Clara', 'Dew', 'John', 'Ravi', 'Ram'];
  return (
    <>
     <ul>
        {students.map((student) => <Stud name={student} />)}
      </ul>
    </>
  );
}

I want the alerts to be displayed only if I click on the li element but in my my code it continuously pops up alert as soon as page loads!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

That's because you are calling the function when the page loads. You have to pass a function to onClick, not call the function directly:

onClick={() => clickhandle(props)}
about 4 years ago · Juan Pablo Isaza 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