{{announcement.body}}
{{announcement.title}}

Rendering Arrays of Components With React

DZone 's Guide to

Rendering Arrays of Components With React

React doesn't support the use of a for() loop in its render method, so we'll have to get creative. Read on as one dev explains a solution.

· Web Dev Zone ·
Free Resource

React doesn't support the use of a for() loop in its 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 follow-up post.



If you enjoyed this article and want to learn more about React, check out this collection of tutorials and articles on all things React.

Topics:
web dev ,react tutorial ,react components ,javascript arrays

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}