` syntax:
```js
import { Fragment } from 'react';
// ...
const listItems = people.map(person =>
{person.name}
{person.bio}
);
```
Fragments disappear from the DOM, so this will produce a flat list of ``, `
`, `
`, `
`, and so on.
### Where to get your `key`
Different sources of data provide different sources of keys:
* **Data from a database:** If your data is coming from a database, you can use the database keys/IDs, which are unique by nature.
* **Locally generated data:** If your data is generated and persisted locally (e.g. notes in a note-taking app), use an incrementing counter or a package like [`uuid`](https://www.npmjs.com/package/uuid) when creating items.
### Rules of keys
* **Keys must be unique among siblings.** However, it’s okay to use the same keys for JSX nodes in _different_ arrays.
* **Keys must not change** or that defeats their purpose! Don't generate them while rendering.
### Why does React need keys?
Imagine that files on your desktop didn't have names. Instead, you'd refer to them by their order -- the first file, the second file, and so on. You could get used to it, but once you delete a file, it would get confusing. The second file would become the first file, the third file would be the second file, and so on.
File names in a folder and JSX keys in an array serve a similar purpose. They let us uniquely identify an item between its siblings. A well-chosen key provides more information than the position within the array. Even if the _position_ changes due to reordering, the `key` lets React identify the item througout its lifetime.
You might be tempted to use an item's index in the array as its key. In fact, that's what React will use if you don't specify a `key` at all. But the order in which you render items will change over time if an item is inserted, deleted, or if the array gets reordered. Index as a key often leads to subtle and confusing bugs.
Similarly, do not generate keys on the fly, e.g. with `key={Math.random()}`. This will cause keys to never match up between renders, leading to all your components and DOM being recreated every time. Not only is this slow, but it will also lose any user input inside the list items. Instead, use a stable ID based on the data.
Note that your components won't receive `key` as a prop. It's only used as a hint by React itself. If your component needs an ID, you have to pass it as a separate prop: ``.
On this page you learned:
* How to move data out of components and into data structures like arrays and objects.
* How to generate sets of similar components with JavaScript's `map()`.
* How to create arrays of filtered items with JavaScript's `filter()`.
* Why and how to set `key` on each component in a collection so React can keep track of each of them even if their position or data changes.
### Splitting a list in two
This example shows a list of all people.
Change it to show two separate lists one after another: **Chemists** and **Everyone Else**. Like previously, you can determine whether a person is a chemist by checking if `person.profession === 'chemist'`.
```js App.js
import { people } from './data.js';
import { getImageUrl } from './utils.js';
export default function List() {
const listItems = people.map(person =>
{person.name}:
{' ' + person.profession + ' '}
known for {person.accomplishment}
);
return (
Scientists
);
}
```
```js data.js
export const people = [{
id: 0,
name: 'Creola Katherine Johnson',
profession: 'mathematician',
accomplishment: 'spaceflight calculations',
imageId: 'MK3eW3A'
}, {
id: 1,
name: 'Mario José Molina-Pasquel Henríquez',
profession: 'chemist',
accomplishment: 'discovery of Arctic ozone hole',
imageId: 'mynHUSa'
}, {
id: 2,
name: 'Mohammad Abdus Salam',
profession: 'physicist',
accomplishment: 'electromagnetism theory',
imageId: 'bE7W1ji'
}, {
id: 3,
name: 'Percy Lavon Julian',
profession: 'chemist',
accomplishment: 'pioneering cortisone drugs, steroids and birth control pills',
imageId: 'IOjWm71'
}, {
id: 4,
name: 'Subrahmanyan Chandrasekhar',
profession: 'astrophysicist',
accomplishment: 'white dwarf star mass calculations',
imageId: 'lrWQx8l'
}];
```
```js utils.js
export function getImageUrl(person) {
return (
'https://i.imgur.com/' +
person.imageId +
's.jpg'
);
}
```
```css
ul { list-style-type: none; padding: 0px 10px; }
li {
margin-bottom: 10px;
display: grid;
grid-template-columns: auto 1fr;
gap: 20px;
align-items: center;
}
img { width: 100px; height: 100px; border-radius: 50%; }
```
You could use `filter()` twice, creating two separate arrays, and then `map` over both of them:
```js App.js
import { people } from './data.js';
import { getImageUrl } from './utils.js';
export default function List() {
const chemists = people.filter(person =>
person.profession === 'chemist'
);
const everyoneElse = people.filter(person =>
person.profession !== 'chemist'
);
return (
Scientists
Chemists
Everyone Else
);
}
```
```js data.js
export const people = [{
id: 0,
name: 'Creola Katherine Johnson',
profession: 'mathematician',
accomplishment: 'spaceflight calculations',
imageId: 'MK3eW3A'
}, {
id: 1,
name: 'Mario José Molina-Pasquel Henríquez',
profession: 'chemist',
accomplishment: 'discovery of Arctic ozone hole',
imageId: 'mynHUSa'
}, {
id: 2,
name: 'Mohammad Abdus Salam',
profession: 'physicist',
accomplishment: 'electromagnetism theory',
imageId: 'bE7W1ji'
}, {
id: 3,
name: 'Percy Lavon Julian',
profession: 'chemist',
accomplishment: 'pioneering cortisone drugs, steroids and birth control pills',
imageId: 'IOjWm71'
}, {
id: 4,
name: 'Subrahmanyan Chandrasekhar',
profession: 'astrophysicist',
accomplishment: 'white dwarf star mass calculations',
imageId: 'lrWQx8l'
}];
```
```js utils.js
export function getImageUrl(person) {
return (
'https://i.imgur.com/' +
person.imageId +
's.jpg'
);
}
```
```css
ul { list-style-type: none; padding: 0px 10px; }
li {
margin-bottom: 10px;
display: grid;
grid-template-columns: auto 1fr;
gap: 20px;
align-items: center;
}
img { width: 100px; height: 100px; border-radius: 50%; }
```
In this solution, the `map` calls are placed directly inline into the parent `` elements, but you could introduce variables for them if you find that more readable.
There is still a bit duplication between the rendered lists. You can go further and extract the repetitive parts into a `` component:
```js App.js
import { people } from './data.js';
import { getImageUrl } from './utils.js';
function ListSection({ title, people }) {
return (
<>
{title}
>
);
}
export default function List() {
const chemists = people.filter(person =>
person.profession === 'chemist'
);
const everyoneElse = people.filter(person =>
person.profession !== 'chemist'
);
return (
Scientists
);
}
```
```js data.js
export const people = [{
id: 0,
name: 'Creola Katherine Johnson',
profession: 'mathematician',
accomplishment: 'spaceflight calculations',
imageId: 'MK3eW3A'
}, {
id: 1,
name: 'Mario José Molina-Pasquel Henríquez',
profession: 'chemist',
accomplishment: 'discovery of Arctic ozone hole',
imageId: 'mynHUSa'
}, {
id: 2,
name: 'Mohammad Abdus Salam',
profession: 'physicist',
accomplishment: 'electromagnetism theory',
imageId: 'bE7W1ji'
}, {
id: 3,
name: 'Percy Lavon Julian',
profession: 'chemist',
accomplishment: 'pioneering cortisone drugs, steroids and birth control pills',
imageId: 'IOjWm71'
}, {
id: 4,
name: 'Subrahmanyan Chandrasekhar',
profession: 'astrophysicist',
accomplishment: 'white dwarf star mass calculations',
imageId: 'lrWQx8l'
}];
```
```js utils.js
export function getImageUrl(person) {
return (
'https://i.imgur.com/' +
person.imageId +
's.jpg'
);
}
```
```css
ul { list-style-type: none; padding: 0px 10px; }
li {
margin-bottom: 10px;
display: grid;
grid-template-columns: auto 1fr;
gap: 20px;
align-items: center;
}
img { width: 100px; height: 100px; border-radius: 50%; }
```
A very attentive reader might notice that with two `filter` calls, we check each person's profession twice. Checking a property is very fast, so in this example it's fine. If your logic was more expensive than that, you could replace the `filter` calls with a loop that manually constructs the arrays and checks each person once.
In fact, if `people` never change, you could move this code out of your component. From React's perspective, all that matters if that you give it an array of JSX nodes in the end. It doesn't care how you produce that array:
```js App.js
import { people } from './data.js';
import { getImageUrl } from './utils.js';
let chemists = [];
let everyoneElse = [];
people.forEach(person => {
if (person.profession === 'chemist') {
chemists.push(person);
} else {
everyoneElse.push(person);
}
});
function ListSection({ title, people }) {
return (
<>
{title}
>
);
}
export default function List() {
return (
Scientists
);
}
```
```js data.js
export const people = [{
id: 0,
name: 'Creola Katherine Johnson',
profession: 'mathematician',
accomplishment: 'spaceflight calculations',
imageId: 'MK3eW3A'
}, {
id: 1,
name: 'Mario José Molina-Pasquel Henríquez',
profession: 'chemist',
accomplishment: 'discovery of Arctic ozone hole',
imageId: 'mynHUSa'
}, {
id: 2,
name: 'Mohammad Abdus Salam',
profession: 'physicist',
accomplishment: 'electromagnetism theory',
imageId: 'bE7W1ji'
}, {
id: 3,
name: 'Percy Lavon Julian',
profession: 'chemist',
accomplishment: 'pioneering cortisone drugs, steroids and birth control pills',
imageId: 'IOjWm71'
}, {
id: 4,
name: 'Subrahmanyan Chandrasekhar',
profession: 'astrophysicist',
accomplishment: 'white dwarf star mass calculations',
imageId: 'lrWQx8l'
}];
```
```js utils.js
export function getImageUrl(person) {
return (
'https://i.imgur.com/' +
person.imageId +
's.jpg'
);
}
```
```css
ul { list-style-type: none; padding: 0px 10px; }
li {
margin-bottom: 10px;
display: grid;
grid-template-columns: auto 1fr;
gap: 20px;
align-items: center;
}
img { width: 100px; height: 100px; border-radius: 50%; }
```
### Nested lists in one component
Make a list of recipes from this array! For each recipe in the array, display its title as an `` and list its ingredients in a ``.
This will require nesting two different `map` calls.
```js App.js
import { recipes } from './data.js';
export default function RecipeList() {
return (
Recipes
);
}
```
```js data.js
export const recipes = [{
id: 'greek-salad',
name: 'Greek Salad',
ingredients: ['tomatoes', 'cucumber', 'onion', 'olives', 'feta']
}, {
id: 'hawaiian-pizza',
name: 'Hawaiian Pizza',
ingredients: ['pizza crust', 'pizza sauce', 'mozzarella', 'ham', 'pineapple']
}, {
id: 'hummus',
name: 'Hummus',
ingredients: ['chickpeas', 'olive oil', 'garlic cloves', 'lemon', 'tahini']
}];
```
Here is one way you could go about it:
```js App.js
import { recipes } from './data.js';
export default function RecipeList() {
return (
Recipes
{recipes.map(recipe =>
{recipe.name}
{recipe.ingredients.map(ingredient =>
-
{ingredient}
)}
)}
);
}
```
```js data.js
export const recipes = [{
id: 'greek-salad',
name: 'Greek Salad',
ingredients: ['tomatoes', 'cucumber', 'onion', 'olives', 'feta']
}, {
id: 'hawaiian-pizza',
name: 'Hawaiian Pizza',
ingredients: ['pizza crust', 'pizza sauce', 'mozzarella', 'ham', 'pineapple']
}, {
id: 'hummus',
name: 'Hummus',
ingredients: ['chickpeas', 'olive oil', 'garlic cloves', 'lemon', 'tahini']
}];
```
Each of the `recipes` already includes an `id` field, so that's what the outer loop uses for its `key`. There is no ID you could use to loop over ingredients. However, it's reasonable to assume that the same ingredient won't be listed twice within the same recipe, so its name can serve as a `key`. Alternatively, you could change the data structure to add IDs, or use index as a `key` (with the caveat that you can't safely reorder ingredients).
### Extracting a list item component
This `RecipeList` component contains two nested `map` calls. To simplify it, extract a `Recipe` component from it which will accept `id`, `name`, and `ingredients` props. Where do you place the outer `key` and why?
```js App.js
import { recipes } from './data.js';
export default function RecipeList() {
return (
Recipes
{recipes.map(recipe =>
{recipe.name}
{recipe.ingredients.map(ingredient =>
-
{ingredient}
)}
)}
);
}
```
```js data.js
export const recipes = [{
id: 'greek-salad',
name: 'Greek Salad',
ingredients: ['tomatoes', 'cucumber', 'onion', 'olives', 'feta']
}, {
id: 'hawaiian-pizza',
name: 'Hawaiian Pizza',
ingredients: ['pizza crust', 'pizza sauce', 'mozzarella', 'ham', 'pineapple']
}, {
id: 'hummus',
name: 'Hummus',
ingredients: ['chickpeas', 'olive oil', 'garlic cloves', 'lemon', 'tahini']
}];
```
You can copy-paste the JSX from the outer `map` into a new `Recipe` component and return that JSX. Then you can change `recipe.name` to `name`, `recipe.id` to `id`, and so on, and pass them as props to the `Recipe`:
```js
import { recipes } from './data.js';
function Recipe({ id, name, ingredients }) {
return (
{name}
{ingredients.map(ingredient =>
-
{ingredient}
)}
);
}
export default function RecipeList() {
return (
Recipes
{recipes.map(recipe =>
)}
);
}
```
```js data.js
export const recipes = [{
id: 'greek-salad',
name: 'Greek Salad',
ingredients: ['tomatoes', 'cucumber', 'onion', 'olives', 'feta']
}, {
id: 'hawaiian-pizza',
name: 'Hawaiian Pizza',
ingredients: ['pizza crust', 'pizza sauce', 'mozzarella', 'ham', 'pineapple']
}, {
id: 'hummus',
name: 'Hummus',
ingredients: ['chickpeas', 'olive oil', 'garlic cloves', 'lemon', 'tahini']
}];
```
Here, `` is a syntax shortcut saying "pass all properties of the `recipe` object as props to the `Recipe` component". You could also write each prop explicitly: ``.
**Note that the `key` is specified on the `` itself rather than on the root `` returned from `Recipe`.** This is because this `key` is needed directly within the context of the surrounding array. Previously, you had an array of `
`s so each of them needed a `key`, but now you have an array of `
`s. In other words, when you extract a component, don't forget to leave the `key` outside the JSX you copy and paste.
### List with a separator
This example renders a famous haiku by Katsushika Hokusai, with each line wrapped in a `` tag. Your job is to insert an `
` separator between each paragraph. Your resulting structure should look like this:
```js
I write, erase, rewrite
Erase again, and then
A poppy blooms.
```
A haiku only contains three lines, but your solution should work with any number of lines. Note that `
` elements only appear *betweeen* the `` elements, not in the beginning or the end!
```js
const poem = {
lines: [
'I write, erase, rewrite',
'Erase again, and then',
'A poppy blooms.'
]
};
export default function Poem() {
return (
{poem.lines.map((line, index) =>
{line}
)}
);
}
```
```css
body {
text-align: center;
}
p {
font-family: Georgia, serif;
font-size: 20px;
font-style: italic;
}
hr {
margin: 0 120px 0 120px;
border: 1px dashed #45c3d8;
}
```
(This is a rare case where index as a key is acceptable because a poem's lines will never reorder.)
You'll either need to convert `map` to a manual loop, or use a fragment.
You can write a manual loop, inserting `
` and `...
` into the output array as you go:
```js
const poem = {
lines: [
'I write, erase, rewrite',
'Erase again, and then',
'A poppy blooms.'
]
};
export default function Poem() {
let output = [];
// Fill the output array
poem.lines.forEach((line, i) => {
output.push(
);
output.push(
{line}
);
});
// Remove the first
output.shift();
return (
{output}
);
}
```
```css
body {
text-align: center;
}
p {
font-family: Georgia, serif;
font-size: 20px;
font-style: italic;
}
hr {
margin: 0 120px 0 120px;
border: 1px dashed #45c3d8;
}
```
Using the original line index as a `key` doesn't work anymore because each separator and paragraph are now in the same array. However, you can give each of them a distinct key using a suffix, e.g. `key={i + '-text'}`.
Alternatively, you could render a collection of fragments which contain `
` and `...
`. However, the `<> >` shorthand syntax doesn't support passing keys, so you'd have to write `` explicitly:
```js
import React, { Fragment } from 'react';
const poem = {
lines: [
'I write, erase, rewrite',
'Erase again, and then',
'A poppy blooms.'
]
};
export default function Poem() {
return (
{poem.lines.map((line, i) =>
{i > 0 &&
}
{line}
)}
);
}
```
```css
body {
text-align: center;
}
p {
font-family: Georgia, serif;
font-size: 20px;
font-style: italic;
}
hr {
margin: 0 120px 0 120px;
border: 1px dashed #45c3d8;
}
```
Remember, fragments (often written as `<> >`) let you group JSX nodes without adding extra ``s!