Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does React warn me against binding a component method to the object?

I have this here component. I want to pass down a call handler to each listElement I create. If I do it like below, with bind(this), it works properly. The problem is that I get this warning from React in the console: bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call.

var MyList = React.createClass({
  render: function () {
    var listElements = this.props.myListValues.map(function (val) {
      return (
        <ListElement onCallHandler={this.props.parentsCallHandler} val={val} />
        );
    }.bind(this));
    return (
      <ul>
          {listElements}
      </ul>
      );
  }
});

If I don't bind it, my children don't know about the call handler. What could I have done differently?

PS:

I know about destructuring assignments, like explained http://facebook.github.io/react/docs/transferring-props.html#transferring-with-...-in-jsx, but I don't want to use Harmony.

like image 901
andersem Avatar asked Nov 06 '14 18:11

andersem


People also ask

Why do we need to bind methods in React class component?

Binding methods helps ensure that the second snippet works the same way as the first one. With React, typically you only need to bind the methods you pass to other components. For example, <button onClick={this.handleClick}> passes this.handleClick so you want to bind it.

How would you avoid binding in React?

To avoid the need for binding we have something introduced in ES6 as arrow functions. Using the arrow function to call this. setState will lead to avoid the use of bind.

What is method binding in React?

ReactJS bind() Method The bind() is an inbuilt method in React that is used to pass the data as an argument to the function of a class based component.

Which functions allow to bind the context of the components?

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.


2 Answers

The error is coming from somewhere else in the code. You get the error when you do this.someFunction.bind(something) and something isn't null.

this.someFunction.bind({}, foo);    // warning
this.someFunction.bind(this, foo);  // warning, you're doing this
this.someFunction.bind(null, foo);  // okay!

Do a search for .bind(this in your code to find the offending line.

like image 195
Brigand Avatar answered Sep 23 '22 06:09

Brigand


Here is updated docs example

React.createClass({
  onClick: function(event) {/* do something with this */},
  render: function() {
    return <button onClick={this.onClick} />;
  }
});

Update in ReactJS Docs

like image 40
Upworks Avatar answered Sep 19 '22 06:09

Upworks