starcorn
starcorn

Reputation: 8531

reactjs - How to render a component which render return a component?

for the following example I have a component GetCurrentVisitor which renders Visitors.

However it will only render the <h1> tag and the table is empty. I suspect I need to use ReactDOM to render Vistors component as well. But how to do it?

var VISITORS = [
        {
            first_name: 'Harry',
            last_name: 'Potter'
        },
        {
            first_name: 'Hermione',
            last_name: 'Granger'
        }
    ]

class GetCurrentVisitors extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visitors: VISITORS
        }
    }

    render () {
        return (
            <div>
                <h1>Current visitors</h1>
                <Visitors visitors={this.state.visitors} />
            </div>
        );
    }
}

class Visitors extends React.Component {
    constructor(props) {
        super(props);
    }
    render () {
        return (
            <table>
                {this.props.visitors.forEach(
                    function(visitor) {
                        <tr>
                            <td>
                            {console.log('from: ', visitor.first_name)}
                            {visitor.first_name}
                            </td>
                        </tr>
                    })}
            </table>
        );
    }
}

ReactDOM.render(
    <GetCurrentVisitors />, document.getElementById('getcurrentvisitors'))

Upvotes: 2

Views: 593

Answers (2)

The Reason
The Reason

Reputation: 7973

You can also are able to use .forEach but in another way fiddle

render () {
  let itemList = [];
  this.props.visitors.forEach(function(visitor,index) {
    itemList.push(<tr key={index}><td>
        {visitor.first_name}
      </td></tr>
    )
  })
  return (
    <table>
      {itemList}
    </table>
    );
}

As for me Array.prototype.map more easy to use with React. It just another example.

Thanks

Upvotes: 1

Oleksandr T.
Oleksandr T.

Reputation: 77482

In this case you should use .map instead of .forEach

{this.props.visitors.map(function(visitor, index) {
  return <tr key={index}>
    <td>{ visitor.first_name } </td>
  </tr>
})}

Example

Upvotes: 4

Related Questions