Rendering arrays of Components with React

React doesn’t support the use of a for() loop in it’s render method. If you need to render a list of components based on data, one approach is to build a var representing the list of components in a helper function as described here.

Another approach is to use .map() to build an array of Components from an array of values, like this:

this.state.grid.map( (cell, index) => (
<CellComponent key={index} value={this.state.grid[index]}
onChange={this.handleChangeForArrayFields.bind(this, index)}/>
)
)}

In this example, this.state.grid is an array containing values to map to each rendered value attribute on my Component. Each rendered element needs to be unique, so we add the key attribute, and set it to the index from each element that comes out of the map function.

I’ll look at the onChange handler in a followon post.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.