Say that you’ve asked React to render an array of identical, uncontrolled inputs.
So far, so good — they render properly and you can type in them! But let’s think about this a little more.
When React encounters an array of elements with identical
props, despite looking identical to React, it cannot know that they really are identical. For example, say that you check one of the inputs. Now you have four identical elements, but differing internal state.
At first, this isn’t a problem. After all, the state is internal. That’s the whole point.
But say that you then reorder the inputs. As all of the elements are identical, React won’t know that anything has changed, and is unable to reorder the corresponding DOM nodes. To demonstrate, let’s add some labels and a reverse button.
Notice what happens when you check an input and then click reverse.
Doh! The inputs are stuck. Luckily, even if React by itself can’t distinguish between array items, you can always give it a hand. That’s what the special
key prop is for. By providing a
key, you’re giving React a way to keep track of otherwise identical elements.
To see this in action, try adding unique
key props to each of the fields above. Your keys can be strings or numbers — the only thing that matters is that they’re unique. Once you’ve added these, try reversing the list again — if the keys are in the right place, the inputs should be reversed too!
If you’re having any trouble with this, you can check the solution in the editor above — but do give it a shot first!