How can I render a component X amount of times based on a javascript object in React?
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
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad