Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
197
rated 0 times [  200] [ 3]  / answers: 1 / hits: 48997  / 7 Years ago, fri, august 4, 2017, 12:00:00

So say i have an array



var arr=[one, two, three, four];


and i have a component
CardContainer



class CardContainer extends React.Component {   
render() {
return (
<div>
<Card/>
</div>
);
}
}


what im trying to do is
create a number of Card components based on length/count of array arr,
and also
set the text of the div in the Card component from the array.



class Card extends React.Component {   
render() {
return (
<div>
<!--Print arr[i] val using this.props? -->
</div>
);
}
}


So my output will be 4 cards with,
array values printed on each card individually.



This is what ive come up with unsucessfully



class CardContainer extends React.Component {   
render() {
var arr=[one, two, three, four];
var elements=[];
for(var i=0;i<arr.length;i++){
elements.push(<Card value=arr[i]/>);
}
return (
<div>
{elements}
</div>
);
}
}

More From » jquery

 Answers
30

You were close, only forgot to populate the elements array with the Cards, so it's still empty after the loop finishes. And while using map as others suggest is the most idiomatic way to do it in React it still simply generates an array of components which can be generated using a for loop as well:



https://jsfiddle.net/mn0jy5v5/



class Card extends React.Component {   
render() {
return (
<div>
{ this.props.value }
</div>
);
}
}

class CardContainer extends React.Component {
render() {
var arr=[one, two, three, four];
var elements=[];
for(var i=0;i<arr.length;i++){
// push the component to elements!
elements.push(<Card value={ arr[i] } />);
}
/* the for loop above is essentially the same as
elements = arr.map( item => <Card value={ item } /> );
The result is an array of four Card components. */
return (
<div>
{elements}
</div>
);
}
}

[#56870] Tuesday, August 1, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daquanmilesw

Total Points: 57
Total Questions: 102
Total Answers: 110

Location: Wallis and Futuna
Member since Sat, Aug 6, 2022
2 Years ago
;