Rendering Logic

Conditional Rendering

We use javascript for conditional rendering

The Ternary Operator (? :)

  • Used for "If this, then that, else the other."
  • This is the most common way to switch between two components.
function Greeting({ isLoggedIn }) {
  return <div>{isLoggedIn ? <UserDashboard /> : <LoginButton />}</div>;
}

Short-Circuit Evaluation (&&)

  • Used for "If this is true, show it. If false, show nothing."
  • This exploits the way JavaScript evaluates AND logic.
function Mailbox({ unreadMessages }) {
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 && (
        <h2>You have {unreadMessages.length} unread messages.</h2>
      )}
    </div>
  );
}

Returning null

If we want a component to hide itself based on a prop, return null.

function Banner({ show }) {
  if (!show) {
    return null; // Renders nothing
  }
  return <div className="banner">Warning!</div>;
}

Lists & Keys

To render a list of items, we use the JavaScript array method .map(). We transform an array of data into an array of JSX elements.

Syntax

const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
  { id: 3, name: "Charlie" },
];
 
function UserList() {
  return (
    <ul>
      {users.map((user) => (
        // Every item in a list MUST have a unique 'key' prop
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

The key Prop - Why do we need keys?

When we render a list, React needs to know which items changed, were added, or were removed.

  • Without Keys: If we insert an item at the top of the list, React doesn't know we inserted one. It thinks we changed the text of Item 1, changed the text of Item 2, etc. It re-renders every single item.
  • With Unique Keys: React sees the key and says, "Oh, Key #3 is still Key #3, it just moved down. I don't need to re-render it."

The Index as Key Anti-Pattern

Avoid doing this: users.map((user, index) => <li key={index}>...</li>)

  • Why is it bad? The index is not stable. If we delete the first item, the second item (previously index 1) becomes index 0. React gets confused and might reuse the state of the old index 0 for the new index 0.
  • Rule: Only use index if the list is completely static (never changes, never filters, never reorders). Otherwise, use a unique ID (like database ID).

📝 Summary Table

ConceptDefinitionWhen to use
Ternary (? :)cond ? A : BWhen rendering one of two options.
Short-Circuit (&&)cond && AWhen showing/hiding a single option.
.map()Array method.To loop through data and return JSX.
key PropA unique string/number.Required for every item in a list.
Index as KeyUsing array index.Avoid unless list is static.

🛑 Stop and Think

1. If we write count && <h1>Messages</h1> and count is 0, what will appear on the screen? A hidden element or the number 0?

The number 0 will appear on the screen.

  • Why: This is a classic JavaScript "gotcha." The && operator returns the value of the first falsy operand it finds. Since 0 is falsy, the expression short-circuits and returns 0.

  • React's Behavior: React ignores false, null, and undefined (renders nothing), but it renders numbers. Since the expression returned 0, React prints "0" on the UI.

  • The Fix: Always force the condition to be a real boolean.

    • count > 0 && <h1>Messages</h1> (Recommended)

2. What happens if two items in the same list have the exact same key?

React will throw a warning in the console (Encountered two children with the same key...) and we may experience rendering bugs.

  • Why: React uses keys to match the Virtual DOM to the Real DOM. If two items share a key, React cannot distinguish between them. If we try to update the state of Item A, React might accidentally update Item B, or delete the wrong item entirely.

3.Is it okay to use index as a key for a footer navigation menu (e.g., "About", "Contact", "Terms") that never changes?

Yes, it is perfectly fine.

  • Why: The problem with indexes arises only when the list order changes (sorting, filtering, adding/removing).
  • The Rule: If the list is Static (the items never change order and are never added/removed during the user's session), the index is a stable and valid key.