I'm following the Thinking in React Tutorial and on Part 2 below see that the var rows
is interpolated into the markup through JSX. How does JSX know to break out each markup item inside the array? Because to me, the interpolation of {rows}
will simply return an array of markup rather than each markup row laid out one by one. So I see it returning [rowA, rowB, ...]
instead of <rowA /> <rowB /> ...
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>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
},
});
Curly braces are a way to execute arbitrary JavaScript expressions inline (including a simple object) and have React evaluate that and render the result.
When React sees {rows}
, this is what it thinks:
"oh cool, I have a variable to render. Oh look, it's an array! What's in the array? Oh I see that the first item is a React element called ProductCategoryRow
, I'll go render that. NEXT! I see the next one is a ProductRow
, I'll go render that"
and so on.
Since you're the curious type :) here's the source that seems to check to see if the item is an Array, if so it renders each item as it would any single item.