Lesson 8 of 20

Conditional Rendering

Rendering Based on Conditions

In React, you can render different UI elements based on conditions using JavaScript expressions inside JSX. The most common patterns are the ternary operator and the logical AND (&&) operator.

You can also use early returns or if/else statements before the return to handle more complex conditions.

Example
function Dashboard({ isLoggedIn, isAdmin, notifications }) {
  // Early return pattern
  if (!isLoggedIn) {
    return <p>Please log in to continue.</p>;
  }

  return (
    <div>
      {/* Ternary operator */}
      <h1>{isAdmin ? 'Admin Dashboard' : 'User Dashboard'}</h1>

      {/* Logical AND — renders only if true */}
      {isAdmin && <button>Manage Users</button>}

      {/* Conditional with multiple outcomes */}
      {notifications.length > 0 ? (
        <p>You have {notifications.length} notifications</p>
      ) : (
        <p>No new notifications</p>
      )}
    </div>
  );
}