React Conditional Rendering: Patterns & Clean Code Techniques

In React applications, user interfaces are rarely static. You often need to render a loading spinner while fetching data, display a login form if a user is unauthenticated, or show an error banner if an API call fails. In React, conditional rendering works the exact same way conditions work in regular JavaScript.

Approach 1: Standard JavaScript if / else Statements

Use an if...else block outside your returned JSX when you want to return entirely different layout trees:

function UserGreeting({ isLoggedIn, username }) {
  if (isLoggedIn) {
    return <h2>Welcome back, {username}! <button>Logout</button></h2>;
  } else {
    return <h2>Please <a href="/login">Log In</a> to continue.</h2>;
  }
}

Approach 2: The Ternary Operator (? :) Inside JSX

When toggling small pieces of markup inside a larger layout, the ternary operator (condition ? trueMarkup : falseMarkup) is the cleanest technique:

function ProfileBadge({ isVerified }) {
  return (
    <div className="profile-container">
      <h3>Priya Sharma</h3>
      <p>
        Account Status: {isVerified ? (
          <span style={{ color: '#5dbe59', fontWeight: 'bold' }}>✓ Verified Author</span>
        ) : (
          <span style={{ color: '#ef4444' }}>Unverified Account</span>
        )}
      </p>
    </div>
  );
}

Approach 3: Logical AND (&&) Short-Circuit Operator

When you want to render an element only when a condition is true, and render nothing when it is false, use the logical && operator:

function Mailbox({ unreadMessages }) {
  return (
    <div className="mailbox-card">
      <h2>Inbox Notification</h2>
      {/* Renders badge only if unread count is greater than zero */}
      {unreadMessages.length > 0 && (
        <span className="badge">
          You have {unreadMessages.length} new messages!
        </span>
      )}
    </div>
  );
}

Approach 4: Preventing Rendering by Returning null

If a component should be completely hidden based on a prop or state flag, return null:

function WarningBanner({ showWarning, message }) {
  // If showWarning is false, render absolutely nothing
  if (!showWarning) {
    return null;
  }

  return (
    <div className="alert-warning">
      <strong>Warning:</strong> {message}
    </div>
  );
}

Next Step: Lists & Keys

Now let us explore how to iterate over data collections and why keys are vital for reconciliation in React Lists & Keys Reconciliation.

Explore Related React JS Tutorials

Accelerate your React mastery by studying these tightly connected core tutorials:

Rendering Lists & Empty States →

Handling empty collections and loading skeletons.

Event-Driven UI Changes →

Switching visual states based on user interaction.

Fallback Error UIs →

Rendering fallback screens on unhandled component crashes.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!