3

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/

1

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.