Lists and Keys

View saved

Map an array to elements

Call map and return JSX for each item.

const todos = [
  { id: 1, text: "Learn JSX" },
  { id: 2, text: "Practice state" },
];

return (
  <ul>
    {todos.map((todo) => (
      <li key={todo.id}>{todo.text}</li>
    ))}
  </ul>
);

Why keys matter

Keys help React match list items across updates. Use a stable unique id from your data, not the array index when items can reorder or delete.

Render a component per item

Extract a list item component when the row markup grows.

function TodoItem({ todo }) {
  return <li>{todo.text}</li>;
}

{todos.map((todo) => (
  <TodoItem key={todo.id} todo={todo} />
))}

Empty lists

Show a friendly message when there is nothing to display.

{todos.length === 0 ? <p>No tasks yet.</p> : <TodoList items={todos} />}

Comments

One comment per signed-in account. Comments are saved with this page’s URL.