Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Iterate and insert components based on count of array

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>
        );
    }
}
like image 210
ViVekH Avatar asked Aug 04 '17 07:08

ViVekH


People also ask

Can you conditionally add attributes to components in React?

In React, adding attributes conditionally is frequently necessary. In React, it is pretty simple. React is sophisticated enough to skip through some properties if the value you supply is untruthful. This is helpful, mainly when adding numerous characteristics conditionally.

How do you repeat over array and create elements in React?

To loop through an array of objects in React:Use the map() method to iterate over the array. The function you pass to map() gets called for each element in the array. The method returns a new array with the results of the passed in function.

Can I put components in an array React?

Certainly. If you want to pass instances of the component, what you're doing is fine except that you need to close those JSX tags: { src: <SVGComponent1 />, ...

Which elements count number does a React component return?

11) How many numbers of elements a valid react component can return? Answer: A is the correct answer. In react component, we can return only one element.


3 Answers

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>
        );
    }
}
like image 159
pawel Avatar answered Nov 05 '22 22:11

pawel


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>
like image 21
Chris Avatar answered Nov 05 '22 21:11

Chris


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>
    );
}
like image 4
hendrixchord Avatar answered Nov 05 '22 21:11

hendrixchord