Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 3.4Rendering lists and conditional content

Rendering a list

Use an array method such as map to transform data into components. Keep the original data as data; do not store JSX in it.

JSX
function TaskList({ tasks }) {
  return (
    <ul>
      {tasks.map((task) => (
        <TaskItem
          key={task.id}
          title={task.title}
          complete={task.complete}
        />
      ))}
    </ul>
  );
}

Choosing keys

A key identifies an item between renders so React can match it with the correct component. Use a stable identifier from the data. Avoid an array index when items can be inserted, removed or reordered; the same index may then refer to a different item.

Conditional rendering

Use ordinary JavaScript: return early for a completely different state, use a ternary when choosing between two expressions, and use && when content is either present or absent.

JSX
{tasks.length === 0
  ? <p>No tasks yet.</p>
  : <TaskList tasks={tasks} />
}

How map becomes components

map runs once per task and returns a new array of TaskItem elements. React renders that array and uses each key during future comparisons. A key is for React and is not automatically available inside TaskItem; pass id={task.id} separately if the child needs it.

Keys need only be unique among siblings. Generate an id when data is created, not while mapping on every render, or the identity keeps changing.

Challenge: filter and render tasks

Render only incomplete tasks. Show an empty-state paragraph when every task is complete and the number remaining above the list.

Suggested steps
  1. Use filter to create remainingTasks.
  2. Use its length for the summary and condition.
  3. Map it using each task id as the key.
Feedback 👍
Comments are sent via email to me.