-3

I have made a simple button in react app.

<button onClick={console.log('clicked')}>Click</button>

The problem is that button is continuously click without clicked by me.

4
  • onClick={() => console.log('clicked')} Commented Dec 11, 2020 at 12:00
  • Does this answer your question? Correct use of arrow functions in React Commented Dec 11, 2020 at 12:00
  • 1
    Does this answer your question? onClick event fired before clicking in react Commented Dec 11, 2020 at 12:01
  • 1
    you didn’t bind the console, you’ve just called it. Just wrap the console with a callback function. Commented Dec 11, 2020 at 12:02

2 Answers 2

2
<button onClick={() => console.log('clicked')}>Click</button>

is the solution. When you put paranthesis without using the arrow function, it will automatically execute without waiting for you to click the button

Sign up to request clarification or add additional context in comments.

Comments

0

onClick takes function as a parameter. Try this and it should work correctly:

<button onClick={ () => { console.log('clicked') } }>Click</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.