Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
    )
  }
});
like image 268
James111 Avatar asked Dec 28 '15 02:12

James111


People also ask

How do you show a component multiple times in React?

Here is the correct syntax: import React, { Component } from 'react'; import Panel from './components/Panel'; import Results from './components/Results'; import Intro from './components/Intro'; const questionsMap = [0, 1, 2, 3]; class React extends Component { constructor (props) { super (props); this.

What is conditional rendering in JavaScript?

In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application. Conditional rendering in React works the same way conditions work in JavaScript.

How do I render a specific component?

Forcing an update on a React class component In any user or system event, you can call the method this. forceUpdate() , which will cause render() to be called on the component, skipping shouldComponentUpdate() , and thus, forcing React to re-evaluate the Virtual DOM and DOM state.


1 Answers

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>
    )
}
like image 52
John Shammas Avatar answered Oct 21 '22 06:10

John Shammas