React Iterate and insert components based on count of array
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>
);
}
}
try this using map
class CardContainer extends React.Component {
render() {
var arr=["one", "two", "three", "four"];
return (
<div>
{
arr.map(function(value,i)
{
return <Card value={value} key={i}/>
}
)
}
</div>
);
}
}
You need to use .map method https://facebook.github.io/react/docs/lists-and-keys.html
render() {
var arr=["one", "two", "three", "four"];
return (
<div>
// curly braces for parenthesis
{
arr.map((item, index) => {
<Card value={item} key={index} />
});
}
</div>
);
}
You almost got it right!
You missed the curly-braces around arr[i]
. So a working code would look like:
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>
);
}
}
However I suggest you use map()
to iterate through the array:
map
calls a provided callback function once for each element in an array, in order, and constructs a new array from the results
So try this:
class CardContainer extends React.Component {
render() {
var arr=["one", "two", "three", "four"];
return (
<div>
{arr.map(item => <Card key={item} value={item} />)}
</div>
);
}
}
You can then access your value inside Card
like this:
class Card extends React.Component {
render() {
return (
<div>
{this.props.value}
</div>
);
}
}
You can also rewrite your Card
component into a stateless functional component, like this:
const Card = (props) =>
return (
<div>
{props.value}
</div>
);
}
if you want it more compact:
const Card = props => <div>{props.value}</div>