How can I render a component X amount of times based on a javascript object in React?

- 1 answer

Ad

I'm trying to render an X amount of photos depending on how long the OBJECT (photos) is. I've tried just appending data to a string but it doesn't work. Any good solutions?

var RenderPhotos = React.createClass({
  getInitialState: function() {
      return {
        photos: this.props.photos
      };
  },
  render: function(){
    var photoHolder = "";
    for(var i=0;i<this.props.photos.length;i++){
      photoHolder += ("<View>
        <Text>" { this.props.photos[0].description } "</Text>
      </View>");
    }

    return (
      { photoHolder }
      // <View>
      //   <Text> { this.props.photos[0].description } </Text>
      // </View>
    )
  }
});
Ad

Answer

Ad

UPDATE December 2017: React v16 now allows you to return an array from the render function.


With a React class, your top-level render function MUST return a single component. However, inside your JSX, you can insert a single component, OR an array of components.

Like so:

render() {
    var photoHolder = [];
    for(var i=0;i<this.props.photos.length;i++){
        photoHolder.push(
            (<View>
                <Text>{ this.props.photos[0].description }</Text>
            </View>)
        );  
    }

    return (
        <View>
            {photoHolder}
        </View>
    )
}

EDIT: Here's another solution:

render() {
    return (
        <View>
            {this.props.photos.map((photo, i) => {
                return (
                    <View><Text>{photo.description}</Text></View>
                );
            })}
        </View>
    )
}
Ad
source: stackoverflow.com
Ad