Home / React / Lesson 7

Lists, keys and events

Beginner 8 min read Lesson 7 of 11

Render arrays with map. Each item needs a key that is stable for that item’s identity — usually an id from your data, not the array index if the list can reorder or delete.

function Subjects({ items }) {
  return (
    <ul>
      {items.map((s) => (
        <li key={s.code}>{s.code} — {s.name}</li>
      ))}
    </ul>
  );
}

Wrong keys make React reuse the wrong DOM node (inputs keeping the wrong text is a classic bug).

Events

Pass a function, do not call it: onClick={handle} not onClick={handle()} (unless you intend to run it during render). To pass an argument:

<button type="button" onClick={() => remove(s.code)}>Remove</button>

React uses a synthetic event object. e.preventDefault() still works on forms. e.target.value is the current input string.