React.js create loop through Array

React.js create loop through Array

react loop through array of objects
react for loop array
react loop through object
react map nested array
react map array of objects
react native array of objects
react native map array of objects
react native foreach loop

I'm trying to display a Table of 10 Players. I get the data from via ajax and pass it as props to my Child.

var CurrentGame = React.createClass({

  // get game info
  loadGameData: function() {
    $.ajax({
      url: '/example.json',
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('#GET Error', status, err.toString());
      }.bind(this)
    });
  },

  getInitialState: function(){
    return {data: []};
  },

  componentDidMount: function() {
    this.loadGameData();
  },

  render: function() {
    return (
      <div className="CurrentGame">
        <h1> Current Game Information</h1>
        <PlayerList data={this.state.data}/>
      </div>
    );
  }
});

Now I need a List Component to Render the Players:

var PlayerList = React.createClass({


  render: function() {

    // This prints the correct data
    console.log(this.props.data);

    return (
      <ul className="PlayerList">
        // I'm the Player List {this.props.data}
        // <Player author="The Mini John" />

        {
          this.props.data.participants.map(function(player) {
            return <li key={player}>{player}</li>
          })
        }
      </ul>
    )
  }
});

Which gives me a Uncaught TypeError: Cannot read property 'map' of undefined.

I'm kind of unsure what is happening, my console log displays the correct data but somehow I can't access it in the return.

What am I missing ?


In CurrentGame component you need to change initial state because you are trying use loop for participants but this property is undefined that's why you get error.,

getInitialState: function(){
    return {
       data: {
          participants: [] 
       }
    };
},

also, as player in .map is Object you should get properties from it

this.props.data.participants.map(function(player) {
   return <li key={player.championId}>{player.summonerName}</li>
   // -------------------^^^^^^^^^^^---------^^^^^^^^^^^^^^
})

Example

Iterating & Rendering with Loops in React components, Learn how to loop & output from arrays of data in React. you'll know that we can use Javascript's map method to quickly iterate over our array and create a  I'm trying to display a Table of 10 Players. I get the data from via ajax and pass it as props to my Child. var CurrentGame = React.createClass({ // get game info loadGameData: function() {


As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data with participants.

The alternative to the solution they provided would be to prevent render until participants exist, something like this:

    render: function() {
        if (!this.props.data.participants) {
            return null;
        }
        return (
            <ul className="PlayerList">
            // I'm the Player List {this.props.data}
            // <Player author="The Mini John" />
            {
                this.props.data.participants.map(function(player) {
                    return <li key={player}>{player}</li>
                })
            }
            </ul>
        );
    }

React.js create loop through Array, In CurrentGame component you need to change initial state because you are trying use loop for participants but this property is undefined that's  How to Loop in JSX Using map Function. When I first started with React, I realized quite early that I did not know how to loop through an array and render a list of items. The most common way of doing that is with the map function that will return JSX. You will rarely need a loop other than this one. Below you can see how it works.


You can simply do conditional check before doing map like

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(function(player) {
   return <li key={player.championId}>{player.summonerName}</li>
   })
}

Now a days .map can be done in two different ways but still the conditional check is required like

.map with return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => {
   return <li key={player.championId}>{player.summonerName}</li>
 })
}

.map without return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => (
   return <li key={player.championId}>{player.summonerName}</li>
 ))
}

both the above functionalities does the same

How to loop inside React JSX, How to loop in a React component JSX. to generate a JSX partial, you can create a loop, and then add JSX to an array: Download my free React Handbook, and check out my upcoming Full-Stack JavaScript Bootcamp! If you have a set of elements you need to loop upon to generate a JSX partial, you can create a loop, and then add JSX to an array: const elements = [] //..some array const items = [] for ( const [ index , value ] of elements . entries ()) { items . push ( < Element key = { index } /> ) }


How to For Loop in React (With Examples), Although we can write a for loop in React, ES6 provides the more appropriate ways to loop, or iterate, through an array in React using JavaScript. output a set of <li> tags for each element in the array, thus creating a list:. This answer doesn't even attempt to answer the question. The question was clear, how to convert a for loop to a map'able array (or object) in order to render n number of items in a React component without having an array of items. You solution completely ignores that fact and assumes being passed an array of articles from props.


[React] How to Loop Through Arrays in JSX, The way you do this is by using the JavaScript function `map`. The most common reason that you need to loop through an array is to build an HTML list where  Working with array seems the best for me and it's also good provided by the docs. Keys are not neccessary at all, they are meant to keep the order of your elements. I didn't invent the indexes method for keys, this is written in the docs :P – alex1997 Oct 11 '16 at 18:37


Lists and Keys – React, You can build collections of elements and include them in JSX using curly braces {} . Below, we loop through the numbers array using the JavaScript map()  If you choose not to assign an explicit key to list items then React will default to using indexes as keys. Here is an in-depth explanation about why keys are necessary if you’re interested in learning more. Extracting Components with Keys . Keys only make sense in the context of the surrounding array.