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.
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: