DocsLearn
Lists
To draw a row for each item, map over the list. Give each row a key, and React keeps each row with its item as the list changes around it.
In this lesson
- how to draw a row for each item;
- why each row needs a key;
- how to add, change and take away rows;
- what to show when the list is empty.
A row for each item
const PEOPLE = [
{ id: "ada", name: "Ada Lovelace", role: "Mathematician" },
{ id: "grace", name: "Grace Hopper", role: "Rear admiral" },
{ id: "alan", name: "Alan Turing", role: "Codebreaker" },
];
export default function App() {
return (
<ul className="grid gap-1">
{PEOPLE.map((p) => (
<li key={p.id} className="flex justify-between rounded-md bg-muted px-3 py-2">
<span className="font-medium">{p.name}</span>
<span className="text-sm text-muted-foreground">{p.role}</span>
</li>
))}
</ul>
);
}Keys
key tells React which row is which item. When the list changes, a row moves with its item instead of being drawn again for another one, so what it holds (a field being typed in, a row being animated) stays with the right item. Use what identifies the item: its id, a slug, a code. The position in the list is a key only for a list that never changes.
A list that changes
Keep the list in state, and change it by making a new one:
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
export default function App() {
const [todos, setTodos] = useState([{ id: 1, title: "Buy milk" }]);
const [title, setTitle] = useState("");
const add = (e) => {
e.preventDefault();
if (!title.trim()) return;
setTodos((list) => [...list, { id: Date.now(), title: title.trim() }]);
setTitle("");
};
return (
<div className="grid gap-3">
<form className="flex gap-2" onSubmit={add}>
<Input aria-label="New todo" placeholder="What needs doing?" value={title} onChange={(e) => setTitle(e.target.value)} />
<Button type="submit">Add</Button>
</form>
{todos.length === 0 && <p className="text-sm text-muted-foreground">Nothing to do.</p>}
<ul className="grid gap-1">
{todos.map((t) => (
<li key={t.id} className="flex items-center justify-between rounded-md bg-muted px-3 py-1.5">
{t.title}
<Button variant="ghost" size="sm" onClick={() => setTodos((list) => list.filter((x) => x.id !== t.id))}>Done</Button>
</li>
))}
</ul>
</div>
);
}- Add:
[...list, item]. - Take away:
list.filter((x) => x.id !== id). - Change one:
list.map((x) => (x.id === id ? { ...x, done: true } : x)). - Empty: a condition beside the list says so, and offers what to do.
A list kept in the database, live in every tab, is in Loading data.
Next: respond to clicks and typing, in Events and forms.