learnreact.com is moving to school.reactpatterns.com. Get 50% off while we move.

Learn React

Learn React | <!-- -->Essetial React<!-- --> > <!-- -->Lists with Array.map()

Essetial React

Lists with Array.map()

Now that we have a Pokemon, I’d like to list that Pokemon’s abilities. The ones that come along in the api. Now to work with lists, we need to understand how children work in React. So typically if we had a list we’d have some mark up like this. [Example]. Now all of these lists items are children of this unordered list. children don’t just have to be text and other elements, they can actually be arrays, and those arrays can be filled with these elements. In the case where we have an array of data that we’d like to render elements for, we can use map to do that transformation and return a new array with those elements. This pattern is incredibly powerful and it’s how we do lists in React. Now right here I’m using this static array, but I can change that to display the abilities of my Pokemon. So we’ll map over the abilities array and take each ability. Now the api is a little funky in this area, so it’s actually ability.ability.name. And there we have it. A dynamic list of list items of abilities. As a review let’s go over this again. We have a character. We know that because we’re in this condition which says we have a character, and in our character from the api is an abilities array. We map over that array to create a new array, and in that array, we transform each ability into this list item, and display the name off of that ability. So here it’s chlorophyll and overgrow. There’s one thing that we need to do to help React do the bookkeeping for these dynamic elements, and we see that in this error here. Each child in an array or iterator should have a unique “key” prop. And that error is referring to this chunk of code here, where we are dynamically mapping over this array and creating elements. It wants us to provide a key so that it can know, as elements go in and out , which elements are the same and which ones changed. Unfortunately the pokeapi doesn’t have an id. An id would be ideal, but I think In this case we would be able to get away with ability.name. This is an area where you kind of have to use your best judgement. If you have an id, use it. If you don’t, then you might need to generate a UUID, or just use something that you know is going to be unique enough from render to render. So that’s it for list. Really at this point, you could make 99.7% of the internet.



Keep in touch!

Get notified of new React content and resources

    We respect your privacy. Unsubscribe at any time.