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!
CodePudding user response:
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)}