2

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

2 Answers 2

4

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

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

Comments

1

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

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.