Home > Software design >  What is the difference between these two function calls?
What is the difference between these two function calls?

Time:11-13

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 .

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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

  • Related