I was reading the documentation and practicing some things in the React documentation until I finally entered the event handling section. but I don't understand why when using method in class component we have to bind the function, can anyone explain it? for examples :
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
The point is to keep correct value of this reference. Check this example:
class Example {
private prop = 1;
echoProp() {
console.log(this?.prop);
}
}
const example = new Example();
example.echoProp();
const echoPropRef = example.echoProp;
echoPropRef();
In the console you will see 1 and then undefined. This is because:
Example:echoProp's this reference is instance of Example class, so it see also prop property.
if you pass Example:echoProp's reference to another variable (const echoPropRef = example.echoProp - there is no ()), then this reference is changed into undefined.
bind function "freezes" this reference, so it will be always the same; in you example it will be reference to Toggle class.
The bind is necessary if you use code like
<button onClick={this.handleClick}>
When handleClick is triggered by the button, this value inside handleClick will be the click event (this is js behaviour for event listener), but the click event does not have a setState method, which belongs to the component itself. So you want to bind the method to the component, so that this value inside handleClick will be the Toggle component which has the setState method
The this is problem is a general problem in JS (not limited to React).
Normally inside a method, this refers to the current object instance.
Inside an event listener (even if its a method), this refers to the event target.
The this in this.setState must refer to the Component instance.
So to change the value of this, binding is done in the constructor.
Another solution would be
onClick={(evt)=>{handleClick(evt)}}
In this case handleClick ceases being an event listener and the actual event listener would be the anonymous function inside onClick.
The simplest alternative is :
handleClick=(evt)=>{
this.setState(...)
}
Arrow functions do not have their own this & hence acquire the current object (component) instance as this.
Related
I am following a tutorial about es6 classes and React class components. I understand when new class methods are created, the this keyword can be used to run other methods in the class and to access the instance properties on that class which makes sense. Here is an example from mdn:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
calcArea() {
return this.height * this.width;
}
}
In React class component methods this is again used by event handlers to refer to the event handler method, which tells me the binding at this point inside the render method is still ok. React sample below:
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
As I understand, inside the event handler the binding breaks. I understand how to fix the binding, but what I don't understand is WHY it breaks. A clear, simple explanation to understand this would be appreciated as I'd like to understand. In the render method the this binding works as you can access props and state and the event handler and in the es6 sample you can see this being used in different methods without binding, so why not the React event handler?
The "this" keyword refers to the global object triggering it.
So in a class(like in a method), it will refer to the instance of the object that was created.
In event handlers, the object that triggers the function is the HTMLElement, because onClick is a method of the HTMLButtonElement.
So the "this" keyword will refer to it.
This is why you have to bind "this", so it will refer to the instance of the class and not to that element.
class SomeClass extends Component{
someEventHandler(event){
}
render(){
return <input onChange={------here------}>
}
}
I see different versions of ------here------ part.
// 1
return <input onChange={this.someEventHandler.bind(this)}>
// 2
return <input onChange={(event) => { this.someEventHandler(event) }>
// 3
return <input onChange={this.someEventHandler}>
How are the versions different? Or is it just a matter of preference?
Thank you all for answers and comments. All are helpful, and I strongly recommend to read this link FIRST if you are confused as me about this.
http://blog.andrewray.me/react-es6-autobinding-and-createclass/
Binding is not something that is specifc to React, but rather how this works in Javascript. Every function / block has its own context, for functions its more specific to how its called. The React team made a decision for this to not be bound on custom methods on the class (aka not the builtin methods like componentDidMount), when adding ES6 support (class syntax).
When you should bind the context depends on the functions purpose, if you need to access props, state or other members on the class, then you would need to bind it.
For your example, each is different and it depends on how your component is set up.
Pre binding to your class
.bind(this) is used to bind the this context to your components function. However, it returns a new function reference each render cycle! If you don't want to bind on each usage of the function (like in a click handler) you can pre-bind the function.
a. in your constructor do the binding. aka
class SomeClass extends Component{
constructor(){
super();
this.someEventHandler = this.someEventHandler.bind(this);
}
someEventHandler(event){
}
....
}
b. make your custom functions on the class fat arrow functions. aka
class SomeClass extends Component{
someEventHandler = (event) => {
}
....
}
Runtime binding to your class
few common ways to do this
a. you can wrap your components handler function with an inline lambda (fat arrow) function.
onChange={ (event) => this.someEventHandler(event) }
this can provide additional functionality like if you need to pass additional data for the click handler <input onChange={(event) => { this.someEventHandler(event, 'username') }>. The same can be done with bind
b. you can use .bind(this) as described above.
onChange={ this.someEventHandler.bind(this) }
with additional params <input onChange={ this.someEventHandler.bind(this, 'username') }>
If you want to avoid creating a new function reference but still need to pass a parameter, its best to abstract that to a child component. You can read more about that here
In your examples
// 1
return <input onChange={this.someEventHandler.bind(this)}>
This is just doing a runtime event handler bind to your class.
// 2
return <input onChange={(event) => this.someEventHandler(event) }>
Another runtime bind to your class.
// 3
return <input onChange={this.someEventHandler}>
You are just passing the function as the callback function to trigger when the click event happens, with no additional parameters. Make sure to prebind it!
To summarize. Its good to think about how to optimize your code, each method has a utility / purpose depending on what you need.
Why bind a React function?
When you define a component using an ES6 class, a common pattern is for an event handler to be a method on the class. In JavaScript, class methods are not bound by default. If you forget to bind this.someEventHandler and pass it to onChange, this will be undefined when the function is actually called.
Generally, if you refer to a method without () after it, such as onChange={this.someEventHandler}, you should bind that method.
There three ways to bind your onChange function to the correct context
First
return <input onChange={this.someEventHandler.bind(this)}>
In this one we make use of bind explicitly to function to make the onChange event available as an argument to the eventHandler. We can also send some other parameter with type of syntax like
return <input onChange={this.someEventHandler.bind(this, state.value)}>
Second
return <input onChange={(event) => { this.someEventHandler(event) }>
This is a ES6 syntax, whereby we can specifythe parameters that we want to pass to the someEventHandler function. This is equivalent to .bind(this) however, It also gives us the flexibility to send other attributes along with the event like
return <input onChange={(event, value) => { this.someEventHandler(event, value) }>
Third
Define the function someEventHandler using Arrow function
someEventHandler = () => {
console.log(this); // now this refers to context of React component
}
An arrow function does not have its own this, the this value of the enclosing execution context is used and hence the above function gets the correct context.
or bind it in constructor like
constructor(props) {
super(props);
this.someEventHandler = this.someEventHandler.bind(this);
}
return <input onChange={this.someEventHandler}>
In this method, event is directly attached to the someEventHandler function. No other parameters can be passed this way
I am trying to move over the Auth0 login function as described in their tutorial. I am able to get it work if I use it like this:
<button className="btn" onClick={this.props.route.auth.login.bind(this)}>test</button>
but if I set up the button to call a function I define above the render function like this:
login() {
this.props.route.auth.login.bind(this);
}
And change the onclick to be like this:
onClick={this.login()}
or
onClick={() => this.login()}
Then the auth login modal never opens and i receive no error. Also i added a console.log to login() and I can see it in the console, but the actual login modal never opens? It works in the first example, but not in the others.
The reason I am attempting to move this into a function is because I would like to pass the login function down into a child component later, and I was unable to do so and I believe this to be the root issue thats preventing me.
bind does not call your function:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. docs
Also, you are setting the value of onClick prop to the return value of login. If you want to pass a reference to the function, you have to do it without the ().
Your code should look like this:
<button className="btn" onClick={() => this.login()}>test</button> <!-- You need to keep a reference to `this`, hence the binding -->
Then:
login() {
this.props.route.auth.login();
}
I edited the answer so that it uses an arrow function. However, I prefer not doing that, since it makes the code a bit cumbersome, and rather bind all the functions in the constructor, like #patrick-w-mcmahon did.
Let's say you have a container MyContainer and this container renders a view called MyView. This view has a button that calls a method. MyContainer is going to pass to the MyView the method it needs to use.
MyContainer:
class MyContainer extends React.Component {
constructor(props) {
super(props);
this.myFunc = this.myFunc.bind(this);
}
myFunc() {
console.log("hello world");
}
render() {
return <MyView myClick={this.myFunc}/>;
}
}
MyView:
const MyView = ({ myClick }) => {
return <button onClick={myClick} />;
};
MyView.propTypes = {
myClick: PropTypes.func
};
export default MyView;
You pass the needed function from the container to the view and the view calls its parents function from props. the use of bind() sets this scope to the current scope so that when you call this from a different scope it is going to be the scope of the bind. When you are in the render you run a different scope so you must bind your functions to the current class scope so that this.myReallyCoolFunction() is pointing to the correct scope (your class scope).
.bind() will only bind the object and arguments but won't call (run) the function.
TL;DR Just use .call() instead of .bind()
instead of .bind() you can use
.call(this, args) which is basicaly the same as bind only that call will call (run) the function.
you could also use .apply(), which is basicaly the same as .call() but takes an array with the arguments instead of object like .call()
this way you can avoid arrow functions in you jsx render()
and kind of keeping the line of thought with react.
something like ->
login() {
this.props.route.auth.login.call(this);
}
When you call props function through return(JSX) React takes care of calling it once propagation ends.
This is my todo app made with ReactJS. I am not able to delete todo's properly.
It always removes the last todo, regardless of the one i click.
Example: If i click to delete 'Buy socks', it will remove 'Oi them'. If i try to check my list state in the debugger, it deleted the correct ToDo.
I uploaded the code to GitHub repository, it was setup with create-react-app should be very easy to setup.
From what i understand the todo entry that i delete in the state of the TodoList does not remove the state of the removed children, and therefore it does not cease to exist.
How do i take care of it? What am i doing wrong?
Hint: here is a gist with unnecessary code removed.
Right now your deleteTodo function has the wrong this bound to it. The deleteTodo function wants to set the state of the parent component, and calls this.setState(). However, the this is bound in the child's constructor. You want to bind this to the deleteTodo in the constuctor of the parent component: TodoList.
That way when the function is called, it will correctly set the state of TodoList with the new, filtered list of todos.
So be more specific about the changes needed in the code you posted.
First in the constructor of TodoList, bind deleteTodo
this.deleteTodo = this.deleteTodo.bind(this)
Now when this.setState is called in the deleteTodo function it will be setting the state of the correct component.
Now we need to make sure we correctly pass in the argument of delete todo.
In the Todo component, replace
onClick={this.props.deleteTodo.bind(this,todoText)}
with
function(){this.props.deleteTodo(todoText)}
You do not need to bind here, wrap the deleteTodo function so that when onClick is called the wrapper function calls deleteTodo with the correct argument.
When the element is clicked, the function assigned to the onClick prop will be called, with a click event object as an argument. We set this function up to call deleteTodo with the correct argument, ignoring the event object.
class Todo extends React.Component {
/*...*/
handleDelete() {
this.props.deleteTodo(this.state.text);
}
/*...*/
render() {
let priorityClass = this.switchPriority(this.state.priority);
let completedClass = this.getCompletedClass(this.state.completed);
let todoClasses = classNames(priorityClass, completedClass);
return (
<tr className={todoClasses}>
<td><button ref='deleteTodo' onClick={this.handleDelete.bind(this)} className='close-button'>×</button></td>
<td onClick={this.handleClick} className='todo-row'>{this.state.text}</td>
</tr>);
}
}
class TodoList extends React.Component {
/*...*/
deleteTodo(todoToRemove) {
let newTodos = this.state.todos.filter((_todo) => _todo.text !== todoToRemove);
this.setState({
todos: newTodos
});
}
/*...*/
}
Could you try this ? I think it is because you are binding deleteTodo two times.
Using ES5 development with ReactJS, a component can be stated as the following:
var MyComponent = React.createClass({
alertSomething: function(event) {
alert(event.target);
},
render: function() {
return (
<button onClick={this.alertSomething}>Click Me!</button>
);
}
});
ReactDOM.render(<MyComponent />);
In this example, the this references the object itself, which is the expected natural behavior.
Question
My question is:
How you use ES6 to create components?
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
alertSomething(event) {
alert(event.target);
}
render() {
return (
<button onClick={this.alertSomething.bind(this)}>Click Me!</button>
);
}
}
ReactDOM.render(<MyComponent />);
Knowing that in JavaScript the this references the instantiated object itself when using the new operator, someone can tell me what is the real purpose of using bind? It is something related to the internal mechanisms of React?
one of the purpose of bind in React ES6 classes is that you have to bind manually.
No Autobinding
Methods follow the same semantics as regular ES6 classes, meaning that >they don't automatically bind this to the instance. You'll have to >explicitly use .bind(this) or arrow functions =>:
We recommend that you bind your event handlers in the constructor so they >are only bound once for every instance:
constructor(props) {
super(props);
this.state = {count: props.initialCount};
this.tick = this.tick.bind(this); // manually binding in constructor
}
you can read more from the docs: https://facebook.github.io/react/docs/reusable-components.html
var cat = {
sound: 'Meow!',
speak: function () { console.log(this.sound); }
};
cat.speak(); // Output: "Meow!"
var dog = {
sound: 'Woof!'
};
dog.speak = cat.speak;
dog.speak(); // Output: "Woof!"
var speak = cat.speak;
speak(); // Output: "undefined"
speak = cat.speak.bind(dog);
speak(); // Output: "Woof!"
Explanation:
The value of "this" depends how the function is being called. When you provide this.alertSomething as your button's onClick handler, it changes how it will be called since you are providing a direct reference to that function, and it won't be called against your object instance (not sure if I'm phrasing that right).
The .bind function will return a new function where "this" is permanently set to the value passed to it.
ECMAScript 5 introduced Function.prototype.bind. Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
It's best to do this in your component's constructor so that .bind is happening just once for each of your handlers, rather than on every render.
bind is just core javascript. It's how binding events works. It's not a React concept.
The following article explains it pretty well.
Bounded function in JavaScript is a function that is bounded to a given context. That means no matter how you call it, the context of the call will stay the same.
To create a bounded function out of the regular function, the bind method is used. bind method take context to which you want to bind your function as a first argument. The rest of arguments are arguments that will be always passed to such function. It returns a bounded function as a result.
http://reactkungfu.com/2015/07/why-and-how-to-bind-methods-in-your-react-component-classes/
Also, on a side note, you should do all of your event binding in your constructor, not in your render method. This will prevent multiple bind calls.
Here's another good bit of information on the subject. They say:
We recommend that you bind your event handlers in the constructor so they are only bound once for every instance
https://facebook.github.io/react/docs/reusable-components.html