13

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.

andersem
  • 724
  • 1
  • 8
  • 19

2 Answers2

31

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.

JMM
  • 26,019
  • 3
  • 50
  • 55
Brigand
  • 84,529
  • 20
  • 165
  • 173
  • 1
    Oh, you're right, it was somewhere else. I'm embarrassed now – andersem Nov 07 '14 at 08:06
  • 3
    @FakeRainBrigand It seems that it now doesn't warn in the second case, `.bind(this, foo)`. It does with `.bind(this)`. Tested with react@0.13.1. https://jsfiddle.net/69z2wepo/17453/ And the docs currently show doing just that: https://facebook.github.io/react/tips/communicate-between-components.html. This story of when to bind and when not to in React seems perhaps overly complicated. – JMM Oct 06 '15 at 14:02
  • 4
    The reason why `.bind(null,` works is that, since react autobinds since [v0.4](http://facebook.github.io/react/blog/2013/07/02/react-v0-4-autobind-by-default.html), by doing `.bind(null`, we are essentiall execute `this.methond.bind(this).bind(null, arg1, arg2)`. Just thought some of you may want to know **why** it worked. – Alan Dong Jan 17 '16 at 20:00
4

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

Upworks
  • 267
  • 2
  • 15