+ 5

What could be an example demonstrating the purpose of React "key" props?

I am recently learning and researching about React. For practice purpose, I created a quiz app. And in the app, for every questions, there will be four options. However, I made a component named "Option" to implement it. But when I used them altogether, react suggested me to set a "key" props for every "Option" component. (Line 86) What does this props do actually? Or could we build a real example using this props? Here is the code: https://code.sololearn.com/W1Ba8cd5KO7A/?ref=app

6th May 2020, 1:23 PM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
5 odpowiedzi
+ 9
You may find this interesting https://www.nikgraf.com/blog/using-reacts-key-attribute-to-remount-a-component From issue 186 of React Status
6th May 2020, 8:39 PM
Burey
Burey - avatar
+ 3
This doesn't directly answer your question(I think), but the other day, while I was looking at the React documentation, I found a explanation for this. Basically, the documentation(link is https://reactjs.org/docs/lists-and-keys.html) states: "Keys help React identify which items have changed, are added, or are removed." The page also leads to an "in-depth explanation about why keys are necessary": https://reactjs.org/docs/reconciliation.html#recursing-on-children.
6th May 2020, 1:44 PM
Jianmin Chen
Jianmin Chen - avatar
+ 3
Jianmin Chen Thanks for the links :)) Just now read them. I think I've got why it is used. Actually I read an article where they built something using this props. I was wondering what else could be made :))
6th May 2020, 1:52 PM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
+ 3
key helps react run its codes without error, mainly for react internal use. Beside assigning unique key value, i would never use key for other code manipulation.
6th May 2020, 3:34 PM
Calviղ
Calviղ - avatar
+ 3
Burey and Calviղ Really thanks :))
6th May 2020, 10:18 PM
Arb Rahim Badsa
Arb Rahim Badsa - avatar