🔥 0
0
Lesson 7 of 10 20 min +100 XP

Conditional Rendering

Show different UI based on conditions - a core React pattern.

The Ternary Operator

Perfect for if/else scenarios:

{isLoggedIn ? <LogoutButton /> : <LoginButton />}

Read it as: "If logged in, show logout button, else show login button"

The && Operator

When you only need to show something (no else case):

{unreadCount > 0 && <NotificationBadge count={unreadCount} />}

The badge only renders when there are unread messages.

Multiple Conditions

For more complex logic, use helper functions:

function StatusMessage({ status }) {
  if (status === 'loading') return <Spinner />;
  if (status === 'error') return <ErrorMessage />;
  if (status === 'success') return <SuccessMessage />;
  return null;
}

Conditional Styles

Change styles based on state:

<button
  style={{
    background: isActive ? 'green' : 'gray'
  }}
>
  {isActive ? 'Active' : 'Inactive'}
</button>

See conditionals in action below!

Handling Events