Praneeth Kumar
Praneeth Kumar

Reputation: 3

What is the difference between these two function calls?

Why does onClick={props.onClickFunction(1)}> doest not work ?

Function Button(props) {
  // const handleClick = () => setCounter(counter+1);
    return (
    <button onClick={props.onClickFunction(1)}>
      +{props.increment}
    </button>
  
}

Why should I use another function `

function Button(props) {
  const handleClick = () => props.onClickFunction(1)

return (
    <button onClick={handleClick}>
      +{props.increment}
    </button>
  );
}

`

When I tried declaring handleclick function it's working .

Upvotes: 0

Views: 109

Answers (3)

Yilmaz
Yilmaz

Reputation: 49281

"Click" is an event so you have to pass an event handler function. When click is detected on the element that handler function will run.

 // you are passing an event handler
 <button onClick={handleClick}>

But in this case onClick={props.onClickFunction(1)}, you are passing the return value of props.onClickFunction function and if this function does ont return anything, its return value will be undefined.

Upvotes: 0

Dakeyras
Dakeyras

Reputation: 2251

The difference is perhaps best illustrated by the snippet below, which shows what you're effectively doing in each of your examples.

// top example
handleClick = () => props.onClickFunction(1)

// bottom example
handleClick = props.onClickFunction(1)

You are assigning the result of calling the onClickFunction by mistake, when what you actually want to do is assign a function that calls onClickFunction each time it's called. The following code will also work as intended:

function Button(props) {
    return (
    <button onClick={() => props.onClickFunction(1)}>
      +{props.increment}
    </button>
  
}

Upvotes: 2

Tarmah
Tarmah

Reputation: 159

When a component renders, all statements are executed and expressions are evaluated.When Component renders props.onClickFunction(1) function is called which returns undefined which will cause the button to render as causing nothing to occur.

handleClick on the other hand is a reference to a function. You need to pass the function reference to onClick and later when the click happens , it can be called later by React.

Upvotes: 1

Related Questions