Displaying our messages
We will use the Array.map()
function to iterate over our array of messages, and create an array of divs to display the data.
Array.map()
automatically returns an array, which means we can embed that functionality right into our JSX. This is a common pattern in React (usually for displaying collections of data like this), so it's worth watching closely.
Inside our message-container
, we create opening and closing squiggly brackets:
<div id="message-container"> { } </div>
Then, we call map
on our message array, and pass in a function to create the new message div
:
<div id="message-container"> {this.props.messages.map(msg => ( <div key={msg.id} className="message"> <p>{msg.msg}</p> </div> ))} </div>
If all goes well, you should see the following, with all the messages you've sent:
You can even try writing a new message, and watch it instantly appear in the message container. Magic!
A few notes about the...