Lists, Keys and Conditional Rendering
💻 ReactRender collections with stable keys and show different UI for different states.
Most screens show lists: students, messages, products. Keys help React match items between renders.
- 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} />;
}Practice
- Render an array of subjects with keys.
- Show an empty message when the list is empty.
- 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
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.
Expected Output
A list with an empty state and completed styling.
Lesson Nav
React Course
0/9 lessons completed
- 1 Thinking in Components Tutorial
- 2 Props and Composition Tutorial
- 3 State and Events Tutorial
- 4 Lists, Keys and Conditional Rendering Tutorial
- 5 Forms in React Tutorial
- 6 Effects and Data Fetching Tutorial
- 7 Routing and Layouts Tutorial
- 8 Context and Shared State Tutorial
- 9 Project: A Student Dashboard Project