title: React.js - ForEach as a first-class component?
body: <p>I've heard of react-templates, but I was still wondering it was possible to make a first-class ForEach component.</p>
  <p>My end goal is to make something like this more readable:</p>
  <pre><code>&lt;ul&gt;
    {list.map(function(item, i) {
       return &lt;li&gt;{item}&lt;/li&gt;;
     })}
   &lt;/ul&gt;
  
   // instead?
   &lt;ul&gt;
    &lt;ForEach items=&quot;{list}&quot;&gt;
       &lt;li&gt;{item}&lt;/li&gt;
    &lt;/ForEach&gt;
   &lt;/ul&gt;
  </code></pre>
  <p>Here's my first serious attempt by passing props:</p>
  <pre><code>var ForEach = React.createClass({
     render: function(){
        return (
        &lt;ul&gt;
          {this.props.items.map(function(item, i) {
            return React.Children.map(this.props.children, function(child) {
              return React.addons.cloneWithProps(child, {item: item})
           })
          }.bind(this))}
        &lt;/ul&gt;
      );
    }
  });
  
  var Element = React.createClass({
    render: function(){
      return (
      &lt;li&gt;{this.props.children}&lt;/li&gt;
      );
    }
  });
  
  // usage within some other React.createClass render:
  &lt;ForEach items={['foo', 'bar', 'baz']}&gt;
    &lt;Element&gt;{this.props.item}&lt;/Element&gt;
  &lt;/ForEach&gt;
  </code></pre>
  <p>The challenge I'm running into is what <code>this</code> points to.  By single-stepping with a debugger, I can see that I'm creating cloned elements with <code>this.props.item</code> set, but because <code>{this.props.item}</code> is evaluated in the context of some other enclosing component's <code>render</code> method, <code>this</code> isn't the cloned <code>Element</code> component - it's <code>ForEach</code>'s parent.</p>
  <p><code>{this.props.item}</code> <em>will</em> work inside <code>Element.render</code> but that's not where I want it - I want to be able to hand <code>Element</code> some expression that interpolates the current item.</p>
  <p>Is this just not possible in React, or is there some way that I could have the <code>ForEach</code> component pass down state like current item/index to the nested elements?</p>
  <p><strong>UPDATE</strong> I can get a significant improvement in readability with ES6 arrow functions.  One set of curlies goes away, along with the <code>return</code> (and possibly also a <code>.bind(this)</code> if you reference <code>this</code> inside the loop).</p>
  <pre><code>&lt;ul&gt;
    {list.map((item, i) =&gt;
      &lt;li&gt;{item}&lt;/li&gt;
    )}
  &lt;/ul&gt;
  </code></pre>
  <p>That goes a long way to help with the syntax clunkiness of doing <code>map</code> line.</p>