'What's the difference between onClick ={ () => function()} and onClick = {function()}?
What's the difference between this code:
<button onClick={()=>props.submitHandler(searchInputValue)}>Submit</button>
and
<button onClick={props.submitHandler(searchInputValue)}>Submit</button>
The difference is the first one has the parentheses and the second one doesn't. Without the parentheses, my app seems to be re-render indefinitely. Can someone kindly explain it to me?
Solution 1:[1]
In first one:
<button onClick={()=>props.submitHandler(searchInputValue)}>Submit</button>
This is arrow function and it will trigger only onClick of the button.
In second one:
<button onClick={props.submitHandler(searchInputValue)}>Submit</button>
This is a normal function call , which calls the method as soon the rendering of the component happens.
Solution 2:[2]
The first creates a function that calls submitHandler
with an argument and assigns that function to onClick
.
The second immediately (i.e. during the render step) calls submitHandler
with an argument and assigns the return value to onClick
.
Solution 3:[3]
Remember the fact that a function is assigned to onClick
via {} doesn't mean that it will be triggered on html user request. The {} is a compile time action.
Another words:
onClick=>
{execute what is here at compile time and assign the result into onClick
action}
If you have a props.submitHandler()
function call inside {} it will be executed and return value assigned to onClick.
If you have a ()=>props.submitHandler
it is an arrow function and its execution will be "binded" to onClick user action. Traditional method of doin' it (without using fancy arrow functions) would be
<button onClick={function(){props.submitHandler(searchInputValue)}}>Submit</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Harmandeep Singh Kalsi |
Solution 2 | Quentin |
Solution 3 |