-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.

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • `onClick={() => console.log('clicked')}` – Yousaf Dec 11 '20 at 12:00
  • Does this answer your question? [Correct use of arrow functions in React](https://stackoverflow.com/questions/48699573/correct-use-of-arrow-functions-in-react) – Sinan Yaman Dec 11 '20 at 12:00
  • 1
    Does this answer your question? [onClick event fired before clicking in react](https://stackoverflow.com/questions/39874747/onclick-event-fired-before-clicking-in-react) – Guy Incognito Dec 11 '20 at 12:01
  • 1
    you didn’t bind the console, you’ve just called it. Just wrap the console with a callback function. – Naren Dec 11 '20 at 12:02

2 Answers2

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

Sinan Yaman
  • 5,714
  • 2
  • 15
  • 35
0

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

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