Contenido del Curso
Introduction to React
Introduction to React
Keys in Lists
Let's go back to the example of rendering list items using the map
method.
If you use the above code in your React application, you might see a warning in the browser's developer console:
This warning is because React expects us to assign a unique key
attribute to each list item.
When dealing with a list of elements, especially dynamic ones, we need to assign a key to each element while rendering it. This helps React keep track of all the elements so that if changes occur in the list, data or elements are not lost. This will be better understood while learning about hooks, so don't worry if it doesn't make complete sense.
Remember that it's best practice to assign unique keys to an array of elements to avoid surprises.
The key can be a number or even a string. In this case, we can simply assign the text of the item itself as the key since they are all unique:
It is important to note that list of elements doesn't only refer to the elements inside <ul>
or <ol>
elements.
It can be any container having an array of similar elements. For example, in the previous chapter, we created 36 Block
components inside a <div>
, which makes it qualify as a list.
Task
Following is the code from the previous chapter. Assign unique keys to the Block
components to fix the console warning. The keys should be in the format: (i, j)
where i
and j
are the i
and j
values from the for loops. For-example: (0, 0)
, (0, 1)
, etc.
¡Gracias por tus comentarios!