Adam White
Adam White

Reputation: 1136

Is bind(this) necessary in Thinking in React tutorial example?

Within React's Thinking in React tutorial, in the creation of a ProductTable component, the table is initially created statically in part like this:

var ProductTable = React.createClass({
  render: function() {
    var rows = [];
    var lastCategory = null;
    this.props.products.forEach(function(product) {
      if (product.category !== lastCategory) {
        rows.push(<ProductCategoryRow category={product.category} key={product.category} />);
  }
      rows.push(<ProductRow product={product} key={product.name} />);
      lastCategory = product.category;
    });
   // return table

However, later in the example, the table is created as such:

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));  // <-- this is the question
   // return table

Why is binding necessary here? The context doesn't seem to have changed, so why would the context need to be bound?

Upvotes: 0

Views: 158

Answers (2)

Pranesh Ravi
Pranesh Ravi

Reputation: 19113

That's beacuse .forEach() will have it's own context. So, if use use this within forEach() you may get unexpected error.

That's why you should .bind() the forEach() with the context of the component to use it's context within forEach()

The following example should illustrate this.

a = [1, 2, 3, 4]

b = {
  a: function() {
    console.log(this)
  },
  b: function() {
    a.forEach(function() {
      console.log(this)
    })
  },
  c: function() {
    a.forEach(function() {
      console.log(this)
    }).bind(this)
  }
}
b.a()
b.b()
b.c()

Upvotes: 2

Kafo
Kafo

Reputation: 3656

In the first example, There is no use of this. while in the second, this.props.inStockOnly is used. I'm assuming that you know why the bind(this) is needed since it will bind to the class.

Upvotes: 1

Related Questions