Topic 06 / 14

Conditional Rendering & Lists

~9 min read  //  React Series  //  Coding India

Conditional Rendering

It’s all just JavaScript — return early, use ternaries, use &&:

function Dashboard({ user }) {
  if (!user) {
    return <LoginPrompt />;            // early return — cleanest for big branches
  }

  return (
    <main>
      <h1>Welcome, {user.name}</h1>

      {user.isPro ? <ProBadge /> : <UpgradeBanner />}   {/* either/or */}

      {user.notifications > 0 && (                       {/* show-or-nothing */}
        <p>{user.notifications} new notifications</p>
      )}
    </main>
  );
}

One && trap: {count && <Badge />} renders a literal 0 when count is 0. Use {count > 0 && …} — make the left side a real boolean.

The Loading / Error / Data Pattern

Every data-driven component renders one of three states:

if (isLoading) return <Spinner />;
if (error)     return <ErrorBox message={error} />;
return <CourseList courses={courses} />;

Rendering Lists with map()

const courses = [
  { id: 1, title: "Django", price: 199 },
  { id: 2, title: "React", price: 249 },
];

function CourseList() {
  return (
    <ul>
      {courses.map((course) => (
        <li key={course.id}>
          {course.title} — ₹{course.price}
        </li>
      ))}
    </ul>
  );
}

An array of JSX elements renders as siblings. Filter + map chains work exactly as you’d expect:

{courses
  .filter(c => c.price < 200)
  .map(c => <CourseCard key={c.id} {...c} />)}

Keys — Identity for List Items

The key tells React which rendered item corresponds to which data item, so it can reorder/update/remove DOM nodes correctly instead of rebuilding everything:

  • Use a stable unique id from your data: key={course.id}.
  • Never use the array index for lists that reorder, insert, or delete — items get matched to the wrong DOM (input values jump between rows, animations glitch).
  • Keys go on the outermost element returned by the map.

Empty States

{courses.length === 0 ? (
  <p className="empty">No courses yet — check back soon.</p>
) : (
  <ul>{courses.map(...)}</ul>
)}

Professional UIs design the empty state, not just the happy path. Combined with loading and error states, your component now handles every situation its data can be in.