ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Sunday, November 13, 2022

[FIXED] What is the difference between these two function calls?

 November 13, 2022     javascript, reactjs   

Issue

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 .


Solution

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



Answered By - Yilmaz
Answer Checked By - - Senaida (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix