16

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>
        );
    }
}
usr30911
  • 2,731
  • 7
  • 26
  • 56

5 Answers5

22

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>
        );
    }
}
pawel
  • 35,827
  • 7
  • 56
  • 53
  • That didn't work when I try to pass parameter to function as props. Can you help me? – Ari Jul 08 '19 at 13:03
6

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>
Chris
  • 57,622
  • 19
  • 111
  • 137
  • thanks, how do i access the value using props within Card? – usr30911 Aug 04 '17 at 08:00
  • 1
    Thankyou, dig the stateless functional component approach,cheers! – usr30911 Aug 04 '17 at 08:12
  • While `map` is the usual way to do this it is not magic and doesn't do anything that can not be done using a `for` loop. OP's problem was not that they didn't use `map` but that the `elements` were an empty array even after the for loop finished ;) – pawel Aug 04 '17 at 08:19
  • @pawel, I actually didn't look carefully as to why the code didn't work for OP. I just provided the simplest solution. However, I did take a look now. The problem isn't that the `elements` array is empty, but because the code has a syntax error. It is missing the curly-braces around `` - which is invalid JSX. That said, I will update my answer. Thanks :) – Chris Aug 04 '17 at 08:26
  • @ViVekH, updated answer with more details. Take a look. – Chris Aug 04 '17 at 08:29
  • @Chris `push` has been edited into the question after I have posted my answer ;) The lack of curly braces is a problem as well. – pawel Aug 04 '17 at 09:00
  • @pawel, ah okay, didn't see that. – Chris Aug 04 '17 at 09:02
4

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>
    );
}
Community
  • 1
  • 1
hendrixchord
  • 4,662
  • 4
  • 25
  • 39
2

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>
            );
        }
    }
Vikram Saini
  • 2,713
  • 1
  • 16
  • 33
1

You can try passing an array to the cards class and dynamically generate elements accordingly.

https://jsfiddle.net/69z2wepo/83859/

 class CardContainer extends React.Component {  
        constructor(props){
            super(props);
            this.props=props;
            this.arr=["one", "two", "three", "four"];
        }
        render() { 
            return (
                <div> 
                <Card arr={this.arr}/> //pass your props value
                </div>
            );
        }
    }

your cards class here

class Card extends React.Component {   
    constructor(props){
        super(props);
        this.props=props; //set props value

    }
    render() {
        return (
            <div> 
            {
             // itterate through the array
             this.props.arr.map((value,index)=>(
              <div key={index}>{value}</div>
             ))
            }
            </div>
        );
    }
}
Madhvesh S
  • 139
  • 12