Francisco Maria Calisto Francisco Maria Calisto - 4 months ago 4
Javascript Question

Why is it necessary to use bind when working with ES6 and ReactJS?

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?

jzm jzm
Answer

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