React.js create loop through Array React.js create loop through Array arrays arrays

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 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


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>        );    }


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