Different ways of calling a function in a react component [duplicate] - javascript

This question already has answers here:
React button onClick property:
(2 answers)
Closed 6 months ago.
I am trying to figure out a slight difference here. Say I have a button, which calls a function when clicked. There are two different ways I have done it, one wrong and another right.
ApproachA:
<Input onChange = {function()}/>
ApproachB:
<Input onChange = {function}/>
When using AppeoachA, I am unable to call the function, react throws an error (Too many re-renders. React limits the amount of renders to prevent an infinite loop). However, when I make it an arrow function ( seen in ApproachA.1), I am able to call the function but this approach does not work when the function is working with data input.
Approach A.1
<Input onChange = {()=> function() }/>
When using ApproachB, I do not get an error and the input changes as expected.
Why is this the case? Can someone explain the difference to me? Also, what is the effect of passing an argument in either approach? Does one become more suitable than the other?

function() isn't a function, it is the return value of that function. So while internally, your Input onChange is expecting a function to pass around, calling function() invokes the function and passes that return value instead (which likely causes issues when e.g. a string or number is treated like a function).
Similarly, () => function() is itself a function, which thus doesn't cause these data type issues.

Related

Difference between the ways of function calls [duplicate]

This question already has answers here:
React Function Calling Methods
(3 answers)
Closed 8 months ago.
I have noticed that (at least in React) there are different ways to call a function. I'd say:
onClick={myFunction}
onClick={myFunction()}
onClick={()=>myFunction}
onClick={()=>myFunction()} /*Not sure if I've seen this type*/
Being the case all are correct, what are the difference between them?
onClick={myFunction}
Assigns myFunction to onClick.
onClick={myFunction()}
Calls myFunction immediately and assigns the return value (which needs to be another function) to onClick.
This is often an error caused by people not understanding how () works and wanting the previous syntax.
onClick={()=>myFunction}
Creates a new function and assigns it to onClick.
The new function mentions myFunction but doesn't do anything with it. It is a noop.
It is always a mistake.
onClick={()=>myFunction()}
Creates a new function, which calls myFunction, and assigns it to onClick.
This is usually a waste of resources. It is useful only if myFunction would do something with the event object that onClick passes to the event handler when called and you want to prevent that.
If you were to pass arguments to myFunction (which this example does not) then it would be more generally useful.

React - ES6 - this keyword and arrow function [duplicate]

This question already has answers here:
When do I use parentheses and when do I not?
(5 answers)
Closed 6 years ago.
I'm having questions about when to call a function inside a react component. Sometimes my code breaks when I don't add the brackets to a function call, but not always. Is there some sort of rule i'm missing here?
Doesn't work
// Callback of parent component
<Link onClick={this.props.OnNavigate}>
A link
</Link>
Does work
// Callback of parent component
<Link onClick={this.props.OnNavigate()}>
A link
</Link>
// Callback for function of component
<li onClick={this.toggleDepartments}>other example</li>
foo() is calling the function referenced by foo. foo itself is just a reference to a function, it doesn't call the function.
So, you need to use parenthesis if you want to call the function right here and now.
You have to omit the parentheses if you want to pass the function to other code so it can call the function. That would be the case with event handlers. this.props.OnNavigation should be called when the click event happens (which is some time in the future), not when the component is rendered.
It's good practice to call the function with parens, because when you create a separate js file and link them together with the script tag, you know for certain that it's calling that specific function.

Reason behind undefined 'this' in React Event Handler [duplicate]

This question already has an answer here:
Mystery of "this" in ReactJS
(1 answer)
Closed 3 years ago.
We all know that this will be undefined according to the given code of React. We have many solutions for this problem, like binding, arrow function, etc. I want to know the reason behind this behavior. Please, explain the reason for the behavior of this reference, instead of solutions.
class Foo extends Component {
clickHandler() {
console.log(this);
}
render() {
return <button onClick = {this.clickHandler}> Click Me </button>;
}
}
1)this.clickHandler=this.clickHandler.bind(this) is returns a new function,in which reference to 'this' will refer to the function this is the way of saving the current value of this which is scope during the call to the constructor so that it can be called later the function is called.
if our function dont require access to the state at your component then sure you dont need to bind this.
2)arrow functions automatically bind this, that’s why we don’t need to use .bind() method.

Using parenthesis when calling a function [duplicate]

This question already has answers here:
When do I use parentheses and when do I not?
(5 answers)
Closed 6 years ago.
I have written a function and intend to call it in several circumstances. Here is the function:
var responsive = function(){
$('#menuicon').toggleClass('menuicon-res');
$('.fixed-menu-item').toggleClass('res');
}
In a certain case, calling the function works only when written WITHOUT parenthesis after it:
$('#menuicon').click(responsive);
In another, similar case, calling the function works only when written WITH parenthesis after it:
$('#top').click(function(){
$('html, body').animate({scrollTop: 0},500);
responsive();
});
I think I understand that the first case (w/o parenthesis) returns the function for callback, and the second case (w/ parenthesis) returns the output of the function. Can anyone help explain why the way to call my function changes in these two scenarios?
Thanks;
CPR
In the first scenario you are assigning the function to be run on your click event, and the click event will do the calling. In the second scenario you are calling the function yourself.
The first case you are talking about is hooking up your function as an event listener, which will call the passed function when an event is triggered
//this will execute when "#menuitem" is clicked
$('#menuicon').click(responsive);
Your second case you are calling it yourself, here just putting responsive without actually invoking it will do nothing.
$('#top').click(function(){
$('html, body').animate({scrollTop: 0},500);
responsive();
});

In jquery event why we pass function() as argument? [duplicate]

This question already has answers here:
What is a callback function?
(22 answers)
Closed 7 years ago.
$("p").click(function(){
// action goes here!!
});
In the above jquery code why we pass a function() to the event?
It's called a callback or an anonymous function that you want executed when the event happens. You'll notice it's not just jQuery, but almost all Javascript frameworks will expect one. It's usually whenever you are binding to events, executing functions that might take a while to return, or functions that execute other functions.
But you can also provide it a function name if you want.
function clickedMe(){
alert("Something clicked me");
}
$("p").click(clickedMe)
Because the click method is defined this way (the method parameter ).
See:
click
You have to understand its not a default JavaScript method, this method is defined in the JQuery so you have to call it as it is defined in the method.
Behind the scene actually when JQuery registering any event with DOM its only says to do one thing which is calling your provide method.
The simplest answer: according to documentation.
https://api.jquery.com/click/
When a user clicks a p element, jQuery is supposed to fire an event and execute something. How is it supposed to pass actions, if not using functions?

Categories

Resources