Manage State Locally First Help needed!

Tell us what’s happening:
Hi all,

I am struggling to render multiple list items (li) for each content of the message. I came up with two solutions and the first one works but second one doesn’t. Problem here is that, I think the second solution makes more sense to me. Can anyone advise why the first one works and the second one doesn’t?

*note: both passed the tests but only the first one renders the <li></li> correctly in the browser.

solution1.
image

this will return an array of multiple list items (li)
[<li>message1</li>, <li>message2</li>, <li>...</li>]

solution2.

          {this.state.messages.forEach((message)=>{
            return <li>{message}</li>
          })}

this will return each message content as list element but individually not in an array.
e.g.<li>message1</li> <li>message2</li>

Since we want to render individual <li></li>'s multiple times I think the second solution makes sense but what actually works is the first one.

Your code so far


class DisplayMessages extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: '',
      messages: []
    };
    this.handleChange = this.handleChange.bind(this);
    this.submitMessage = this.submitMessage.bind(this)
  }
  handleChange(event) {
    this.setState({
      input: event.target.value
    })
  }

  submitMessage(){
    this.setState({
      messages: [...this.state.messages, this.state.input],
      input: ""
    })
  }

  render() {
    return (
      <div>
        <h2>Type in a new Message:</h2>
        <input value={this.state.input} onChange={this.handleChange} />
        <button onClick={this.submitMessage}>submit</button>
        <ul>
          {this.state.messages.forEach((message)=>{
            return <li>{message}</li>
          })}
          //{this.state.messages.map((msg) => <li>{msg}</li>)}
        </ul>
      </div>
    );
  }
};

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36.

Link to the challenge:

Second solution isn’t going to work, you are supposed to be rendering a collection of children, not individual items; the child has to either be a single element (in which case, no loop) or an array of elements.

1 Like

Hi @DanCouper

Thanks for the comment. I am not so familiar with React yet. This is a good tip, thanks!

1 Like