New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› React› Lists, Keys and Conditional Rendering

Lists, Keys and Conditional Rendering

💻 React

Render collections with stable keys and show different UI for different states.

Lesson 4 of 9 Tutorial
0 of 9 completed

Most screens show lists: students, messages, products. Keys help React match items between renders.

By the end of this lesson you can:
  • Render a list with map.
  • Use stable keys.
  • Render conditionally.

Rendering a List

Map over the array and return a component for each item. Every item needs a key that is unique and stable.

function StudentList({ students }) {
  return (
    <ul>
      {students.map(student => (
        <li key={student.id}>
          {student.name} — {student.score}
        </li>
      ))}
    </ul>
  );
}

Choosing Keys

Use a database id. Avoid using the array index when items can be added, removed or reordered, because React will attach state to the wrong item.

Conditional UI

Use a ternary for two options and the && operator for show-or-nothing. Keep complex conditions in a variable for readability.

function Results({ loading, error, students }) {
  if (loading) return <p>Loading…</p>;
  if (error) return <p role="alert">{error}</p>;
  if (students.length === 0) return <p>No students yet.</p>;

  return <StudentList students={students} />;
}
Warning Do not use Math.random() as a key. It changes on every render and defeats the purpose.

Practice

  1. Render an array of subjects with keys.
  2. Show an empty message when the list is empty.
  3. Show a loading message before data arrives.

Hands-on exercise

Build a TaskList that accepts tasks.
1. Show 'No tasks yet' when the list is empty.
2. Otherwise render each task with its id as the key.
3. Show a completed style when task.done is true.

Recap

Map creates list UI, stable keys keep it correct and early returns handle loading, error and empty states.

Example

function StudentList({ students }) {
  return (
    <ul>
      {students.map(student => (
        <li key={student.id}>
          {student.name} — {student.score}
        </li>
      ))}
    </ul>
  );
}

Exercises

Exercise 1. Task list states Easy
Build a TaskList that accepts tasks.
1. Show 'No tasks yet' when the list is empty.
2. Otherwise render each task with its id as the key.
3. Show a completed style when task.done is true.
React exercise-1.txt
Expected Output
A list with an empty state and completed styling.

Lesson Nav

Lesson sections