[React MAIN CONCEPTS] 8. Lists and Keys
Lists and Keys
In React, transforming arrays into lists of elements is using the map()
function.
Rendering Multiple Components
You can build collections of elements and include them in JSX using curly braces {}
.
Below, we loop through the numbers array using the JavaScript map()
function. We return a <li>
element for each item. Finally, we assign the resulting array of elements to listItems:
1 | const numbers = [1, 2, 3, 4, 5]; |
We include the entire listItems array inside a <ul>
element, and render it to the DOM:
1 | ReactDOM.render( |
Try it on CodePen - https://codepen.io/gaearon/pen/GjPyQr?editors=0011
This code displays a bullet list of numbers between 1
and 5
.
Basic List Component
Usually you would render lists inside a component.
We can refactor the previous example into a component that accepts an array of numbers and outputs a list of elements.
1 | function NumberList(props) { |
When you run this code, you’ll be given a warning that a key should be provided for list items. A “key” is a special string attribute you need to include when creating lists of elements. We’ll discuss why it’s important in the next section.
Let’s assign a key to our list items inside numbers.map()
and fix the missing key issue.
1 | function NumberList(props) { |
Try it on CodePen - https://codepen.io/gaearon/pen/jrXYRR?editors=0011
Keys
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:
1 | const numbers = [1, 2, 3, 4, 5]; |
The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys:
1 | const todoItems = todos.map((todo) => |
When you don’t have stable IDs for rendered items, you may use the item index
as a key as a last resort:
1 | const todoItems = todos.map((todo, index) => |
We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key - https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318. If you choose not to assign an explicit key to list items then React will default to using indexes as keys.
Here is an in-depth explanation about why keys are necessary if you’re interested in learning more.
Extracting Components with Keys
Keys only make sense in the context of the surrounding array.
For example, if you extract a ListItem component, you should keep the key on the <ListItem />
elements in the array rather than on the <li>
element in the ListItem itself.
Example: Incorrect Key Usage
1 | function ListItem(props) { |
Example: Correct Key Usage
1 | function ListItem(props) { |
Try it on CodePen - https://codepen.io/gaearon/pen/ZXeOGM?editors=0010
A good rule of thumb is that elements inside the map()
call need keys.
Keys Must Only Be Unique Among Siblings
Keys used within arrays should be unique among their siblings. However, they don’t need to be globally unique. We can use the same keys when we produce two different arrays:
1 | function Blog(props) { |
Try it on CodePen - https://codepen.io/gaearon/pen/NRZYGN?editors=0010
Keys serve as a hint to React but they don’t get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name:
1 | const content = posts.map((post) => |
With the example above, the Post component can read props.id, but not props.key.
Embedding map() in JSX
In the examples above we declared a separate listItems variable and included it in JSX:
1 | function NumberList(props) { |
JSX allows embedding any expression in curly braces so we could inline the map() result:
1 | function NumberList(props) { |
Try it on CodePen - https://codepen.io/gaearon/pen/BLvYrB?editors=0010
Sometimes this results in clearer code, but this style can also be abused. Like in JavaScript, it is up to you to decide whether it is worth extracting a variable for readability. Keep in mind that if the map()
body is too nested, it might be a good time to extract a component.
References
[1] Lists and Keys – React - https://reactjs.org/docs/lists-and-keys.html
[2] React – A JavaScript library for building user interfaces - https://reactjs.org/