To display a list of items in react, we can map
(or loop) over that list and return JSX from inside the map function:
<div>
{
props.items.map(item => {
return <p key={item.id}>{item.title}</p>
})
}
</div>
Remember to always include a key
attribute though! That lets React keep track of each list item internally, which gives you better performance, and may save you from subtle bugs
Chris Achard: [0:00] Let's say we have some data here and we want to display that in a list on the web browser. First, let's make a new function component. We'll call that function component MyList for now. That will take props because what we're going to do is render the list down here. We can render it, and we're going to pass the data as props.
[0:19] We might say items = the JavaScript value, DATA. Now this props will have props.items, which will be the data array. We did that mostly for practice in passing props.
[0:34] From MyList, we're going to return JSX. Let's make a <div> wrapper. To loop over this data, we're going to use curly braces to run JavaScript, and we're going to call props.items -- so we have access to the array -- .map(). Map takes a function which will return each item in a loop. From there, we want to return just a paragraph with the title. Inside of here we can say item.title.
[1:04] We're almost done, but on every iteration of the loop we're going to also want to set a key. The key is React specific and lets React keep track of which paragraph tag goes to which row in the data. It means you'll get better performance. We're going to set that to item.id because id is unique across all of these.
[1:22] If we save this now, we get our three list items displayed with our map function.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!