Guillermo Vázquez
Guillermo Vázquez

Reputation: 159

Why is this onClick function getting triggered when typing on input?

I'm really confused because I'm learning to use hooks and I was working on the useState hook, when I stumbled upon this, the onClick function is getting triggered when I type on the input.

This is the code:

import React, {useState} from 'react'

function Hooks() {
  const [count, setInput] = useState("");
  return (
    <React.Fragment>
      <input value={count} onChange={(e) => {setInput(e.target.value)}}>
      </input>
      <button className="btn" value="See Input!" onClick={console.log(count)}>
          Click here!
      </button>
    </React.Fragment>
  )
}

export default Hooks

When I type on the input field, the count gets logged, this is how I fixed it:

import React, {useState} from 'react'

function Hooks() {

  const [count, setInput] = useState("");

  return (
    <React.Fragment>
      <input value={count} onChange={(e) => {setInput(e.target.value)}}>
      </input>

      <button className="btn" value="See Input!" onClick={() => {console.log(count)}}>
          Click here!
      </button>
    </React.Fragment>
  )
}

export default Hooks

As you can see, the only thing that changes is that instead of writing the event of onClick as an arrow function, I just write the line of code. I would understand this wouldn't work but why does this get called whenever I write anything in the input?

Thanks in advance!

Upvotes: 0

Views: 692

Answers (1)

Sawan Patodia
Sawan Patodia

Reputation: 839

The onClick function takes a function. In first case you were calling the function by adding parenthesis around. When state was getting updated return was getting rendered which calls the consol.log() on onCLick.

In second case you have passed the function definition and you are not calling it.

The function gets called when user clicks on the button

Upvotes: 3

Related Questions