Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!