The Codex / Technologies / React / Conditional & List Rendering

Conditional & List Rendering

Showing different UI based on data - if/else patterns in JSX, rendering arrays with .map(), and the key prop explained properly.

What it is, in plain English: Conditional rendering means showing different JSX depending on a condition — done with regular JavaScript (ternaries, &&, early returns), not special React syntax. List rendering means turning an array of data into an array of JSX elements, almost always done with Array.map(). Every element in a rendered list needs a unique, stable key prop so React can correctly track each item across re-renders.

Showing different content based on data

React has no special "if" syntax inside JSX — you use regular JavaScript. The three most common patterns: early return, ternary, and the && operator.

Early return — for completely different UI

function Greeting({ isLoggedIn }) {
  if (!isLoggedIn) {
    return <p>Please log in.</p>;   // returns early, stops here
  }

  return <p>Welcome back!</p>;
}

Ternary — for inline either/or

function StatusIcon({ isOnline }) {
  return (
    <span>
      {isOnline ? "🟢 Online" : "⚫ Offline"}
    </span>
  );
}

&& — for show-or-nothing

function Notification({ message }) {
  return (
    <div>
      {message && <div className="alert">{message}</div>}
      {/* if message is falsy (empty string, null), nothing renders */}
    </div>
  );
}

Rendering a list of items

function FruitList() {
  const fruits = ["Apple", "Banana", "Cherry"];

  return (
    <ul>
      {fruits.map((fruit, index) => (
        <li key={index}>{fruit}</li>
      ))}
    </ul>
  );
}
// .map() transforms each array item into a JSX element
// The result (an array of <li> elements) is placed directly in the JSX

The key prop — required for lists

// Always give list items a unique, STABLE key:
const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
];

<ul>
  {users.map(user => (
    <li key={user.id}>{user.name}</li>   {/* use a real unique id, not array index */}
  ))}
</ul>

// Why? React uses 'key' to match list items across re-renders.
// Without a stable key, React can confuse which item is which when
// the list is reordered, filtered, or items are added/removed.
Try It Yourself (JSX)

Official Sources

The Codex links only to official documentation. No third-party tutorials.