rex
rex

Reputation: 1025

How to loop thorough object and create child component in React.js

I am new to React.js and getting stuck loop thorough child component. I have an object and I need to loop through it which should create child component using the values of that object. Thank you in advance

var o = {
    playerA: {
        name: 'a',
    },

    playerB: {
        name: 'b',
    }
};


var Players = React.createClass({
    getPlayers: function(){
        return o;
    },    

    render: function() {
        return (
            <div>
                <div className="row"> Players</div>
                {this.getPlayers()}
                <Player /> 
            </div>
        );
    }
});


var Player = React.createClass({    
    render: function(){
        return (
            <div className="row" > player {this.name} < /div>
        )
    }
});

React.render(<Players />, document.getElementById('container'));

The result should be:

player a

player b


I have fiddle set up at: http://jsfiddle.net/rexonms/7f39Ljbj/

Upvotes: 3

Views: 4363

Answers (1)

m59
m59

Reputation: 43755

First, you'll iterate over the data with .map so that you can return markup (the child component) for each item. In the child component markup, you pass the data for that item in an attribute.

{Object.keys(yourObject).map(function(key) {
  return (
    // Add a key to the list item, it is mandatory from react
    // What the key consists of if it's the id or not is up to you
    // it needs to be unique though
    <ChildComponent key={key} data={yourObject[key]}/>
  );
})}

The child component's markup can then use that data by binding this.props.data.

<div>Player: {this.props.data.name}</div>

You don't have to use the name "data" for the attribute/property. Something like info={yourObject[key]} with this.prop.info is just as valid.

Working JS Fiddle here.

Upvotes: 6

Related Questions