Adam White Adam White - 2 months ago 9
React JSX Question

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?

Answer

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.