Listing Notes in React
A notes list is a list of notes rendered from state. Each note becomes one list item on the page.
Notes in state
const [notes, setNotes] = useState([
{ id: 1, title: 'Buy milk' },
{ id: 2, title: 'Ship MERN' },
{ id: 3, title: 'Read a book' },
]);One item for each note
{notes.map((note) => <li key={note.id}>{note.title}</li>)}Example
import { useState } from 'react';
export default function App() {
const [notes] = useState([
{ id: 1, title: 'Buy milk' },
{ id: 2, title: 'Ship MERN' },
{ id: 3, title: 'Read a book' },
]);
return (
<div>
<h1>Notes</h1>
<ul>
{notes.map((note) => (
<li key={note.id}>{note.title}</li>
))}
</ul>
</div>
);
}Key points
- The notes live in state as an array of objects.
- The list maps over the array to make one item for each note.
- Each item needs a stable key, and the note id works well.
- The fetch fills this state in the real app.
In this example, state starts with the three seed notes, so the first render shows all three items. The map turns each note into one list item, and the id gives each item its key. In the real app, the fetch fills this state with the notes from the API.
Note
The key stays the same for a note, even when the list order changes.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the list render for each note in state?