Justin M
Justin M

Reputation: 309

How does an anonymous function work in onClick in React component?

When there are two Button components in React, what is the difference between those two?

const add = (x, y) => {
  return x + y
}

Case 1:

<Button onClick={() => add(1, 2)}>Add</Button>

Case 2:

<Button onClick={add(1, 2)}>Add</Button>

Upvotes: 2

Views: 3168

Answers (3)

Arihant Jain
Arihant Jain

Reputation: 847

const add = (x, y) => {
  return x + y
}

In order to pass a value as a parameter through the onClick handler we pass in an arrow function which returns a call to the add function.

<Button onClick={() => add(1, 2)}>Add</Button>

If no parameters are to be passed then you can call directly

const add=()=>{
    return 2+3
}
<Button onClick={add}>Add</Button>

Upvotes: 1

Sundar
Sundar

Reputation: 4650

The differences are

const add = (x, y) => {
  return x + y
}

Case 1: this wait until the user click on the button it'll execute the call

<Button onClick={() => add(1, 2)}>Add</Button>

Case 2: This implementation will give error

<Button onClick={add(1, 2)}>Add</Button>

Case 2.1: This case will bind the function to the click listener

<Button onClick={add}>Add</Button>

Ref: https://medium.com/@omergoldberg/javascript-call-apply-and-bind-e5c27301f7bb

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 371019

The first one will call add(1, 2) and return 3 to the caller of the onClick prop when the button is clicked.

The second one will call add(1, 2) when the JSX is calculated (most likely during render), and will pass 3 as the onClick prop. Case 2 is equivalent to:

<Button onClick={3}>Add</Button>

which is very likely not what you want.

You would usually invoke a function like that only when the function returns another function, eg:

const logNums = (x, y) => () => {
  console.log(x + y);
}
<Button onClick={logNums(1, 2)}>Add</Button>

which will log 3 when the button is pressed.

Upvotes: 4

Related Questions