0

I am trying to follow some tutorials on reactJS and I have a problem with understanding this example https://jsfiddle.net/reactjs/zafjbw1e/light/ . What is the purpose of bind(this) ( line 36) It seems that I can't pass state from parent to child without this bind method.

var ProductTable = React.createClass({
render: function() {
    var rows = [];
    var lastCategory = null;
    this.props.products.forEach(function(product) {
        if (product.name.indexOf(this.props.filterText) === -1 || (!product.stocked && this.props.inStockOnly)) {
            return;
        }
        if (product.category !== lastCategory) {
            rows.push(<ProductCategoryRow category={product.category} key={product.category} />);
        }
        rows.push(<ProductRow product={product} key={product.name} />);
        lastCategory = product.category;
    }.bind(this));
    return (
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>{rows}</tbody>
        </table>
    );
}

});

I still don't understand this code, why we need bind(this) ? Why this.props.products doesn't require bind(this) and this.props.filterText require this ?

Yeynno
  • 331
  • 5
  • 10
  • I also recommend to read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this ... this is nothing specific to React, that's basic JavaScript. – Felix Kling Jun 07 '15 at 22:50
  • I didn't find anything there which help me understand this concept in this react js code. Why you mark this post as duplicated ? – Yeynno Jun 08 '15 at 19:02
  • You are asking what `.bind` does. `.bind` has nothing to do with React. It it used here for the same reason as it used anywhere else. – Felix Kling Jun 08 '15 at 19:03
  • I updated my main question , where I pointed what I don't understand – Yeynno Jun 08 '15 at 19:05
  • And that's exactly what all the other references are trying to explain. All I can do is repeat what is said there: If you don't use `.bind(this)` then `this` inside the `forEach` callback will refer to the global object, not the instance of the React element. The global does not have a `props` property, so `this.props.filterText` fails. I think you just have to take some time to learn how `this` works (also not React specific). – Felix Kling Jun 08 '15 at 19:05
  • @Yeynno - see my comment here for an explanation - http://stackoverflow.com/questions/2236747/use-of-the-javascript-bind-method#comment64021153_10115970 – Myer Jul 11 '16 at 08:38

0 Answers0