Did you know that React has a built-in method that automatically assigns the keys for you when rendering a list of children?
If you are new to React, you might be wondering what keys are and what they do.
If you are familiar to keys and lists, you can skip to the bottom and learn how to automatically assign keys in React.
Introduction to Lists and Keys in React.
Suppose you have the following list of data you would like to render:
const someData = ['Chipata', 'Kasama', 'Mongu',
'Livingstone', 'Mansa', 'Kabwe',
'Ndola', 'Lusaka', 'Solwezi'];
To render this in JSX, we use curly braces and loop through and transform the array using the JavaScript map()
method.
const cities = someData.map(city => (
<li>{city}</li>
));
The map()
callback function will transform each element in our original array into a component that can be rendering. The result from map()
will a be an array of React components (or HTML elements in this case).
We can then render the cities
array inside a <ul>
element like this:
<ul>{cities}</ul>
However, if you run this code, you will notice a warning in the console stating that a key should be proved for list items.
Keys help React identify which components have been added, updated, or removed. They serve as identification for components/elements. You can learn more about why you should provide keys for list items.
Using Keys in React
Keys should be unique. A simple way to correctly map the cities
array above would be to use array indices as keys.
const cities = someData.map((city, i) => (
<li key={i}>{city}</li>
));
If you are working with an array of objects, for example, users
. You could use identifiers from your data as keys.
const users = someData.map((user) => (
<li key={user.id}>{user.full_name}</li>
));
Don't Use Indexes
It is not recommended to use indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Learn more about why Indexes as Keys is an Anti-pattern
Auto-assign Keys
If you don’t have stable IDs for rendered items, you can let React handle this for you using a built-in method.
const cities = React.Children.toArray(
someData.map((city) => <li>{city}</li>)
);
Thanks for learning with me. Happy coding.
I'm offering a remote, 1-on-1 training in React. Interested? Apply here
Top comments (0)