Current section: Rendering Arrays 59 exercises
Problem

Key prop

Loading exercise

Transcript

00:00 In this exercise, we're using a couple of things that we haven't done before. So here we're using this useState hook. You're not going to be interacting with this. We'll talk about this in the React hooks workshop. But this is what allows us to make updates to our UI over time,

00:16 rather than just having everything be right at the initially render time, which is what we've been doing so far. And so as you click on these buttons, it's going to update our UI, and that's where we're going to experience the problems that React is warning us about in here. So your job is to do the very simple thing,

00:36 which is adding a key to these li elements so that we can handle these changes and track or keep track of the data that's associated to the elements so it knows what to do with things. So if you play around with this, you'll notice removing the apple is going to keep the state of this input, and it's going to update the text content here.

00:58 So what's interesting here is that React doesn't know what exactly to do. And so it's saying, okay, well, I'm not going to remove the first item because you still have three items. So I'm going to keep the first item. I'm just going to update the text content of the label because that was its best guess of what it should do. And then it did the same with the second and the third. So it's keeping the state of the input

01:18 because that input didn't get removed, but updating the text content. And as far as React is concerned, that was as good a guess as any, but it's not good enough for us. And so we've got to help React out with a key prop. So that's your job. Add a key prop and then try to remove stuff, and you'll see that things are working much better.