EN
React - why does onClick function fires on component render?
1 answers
0 points
Why is onClick
function being executed on component render?
I have code similar to this:
xxxxxxxxxx
1
const MyComponent = () => {
2
return (
3
<div>
4
<button onClick={alert('some message...')}>Click me!</button>
5
</div>
6
);
7
};
And the alert()
fires before I even click on the button
element.
1 answer
0 points
What you are doing wrong is calling the function instead of passing the function to onClick
property.
Quick solution:
xxxxxxxxxx
1
<button onClick={() => {alert('some message...')}}>Click me!</button>
0 commentsShow commentsAdd comment