ReactJS: onClick gets executed when rendered or loaded without a click
Quite a simple way to solve this.
While working on my group project, I found that onClick is executed without a click. After searching Google, I finally found out why.
The answer is quite simple. Please change your code from this
<button onClick={handleClick()}>Click Me!</button>
to this
<button onClick={() => handleClick()}>Click Me!</button>
The reason for this is simple. When the button is loaded, the onClick function will be evaluated. The function returned from onClick will be executed each time the button is clicked.
So, we need to wrap the function we hope to execute every click into another function, returning the wanted function.
I found the answer on StackOverFlow.