React JSX If Statements

Conditional rendering in React

🔀 Conditional Rendering in JSX

JSX doesn't support if statements directly inside expressions. Instead, use ternary operators, logical AND (&&), or if statements outside JSX to conditionally render components and elements based on conditions and application state.


// Ternary Operator in JSX
const isLoggedIn = true;
const element = <div>{isLoggedIn ? "Welcome!" : "Please login"}</div>;
                                    

Output:

Welcome!

Conditional Rendering Methods

❓

Ternary Operator

condition ? true : false

{isTrue ? <A/> : <B/>}
&&

Logical AND

Render only if condition is true

{isTrue && <Component/>}
📝

If Statement

Use before return statement

if (condition) return <A/>;
🔄

Switch Statement

Multiple conditions

switch(value) { case 'a': ... }

🔹 Ternary Operator

The ternary operator is the most common way to conditionally render in JSX. It evaluates a condition and returns one of two expressions, perfect for simple if-else logic inline.

// Basic Ternary
function Greeting({isLoggedIn}) {
  return (
    <div>
      {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in</h1>}
    </div>
  );
}

// With Components
function Dashboard({hasAccess}) {
  return (
    <div>
      {hasAccess ? <AdminPanel /> : <LoginForm />}
    </div>
  );
}

// Nested Ternary
function Status({status}) {
  return (
    <p>
      {status === 'success' ? 'Done!' : 
       status === 'loading' ? 'Loading...' : 
       'Error'}
    </p>
  );
}

Output (when isLoggedIn = true):

Welcome back!

🔹 Logical AND (&&) Operator

Use the && operator when you only want to render something if a condition is true, with nothing rendered when false. This is cleaner than ternary when you don't need an else case.

// Show element only if condition is true
function Notification({hasMessages}) {
  return (
    <div>
      {hasMessages && <p>You have new messages!</p>}
    </div>
  );
}

// Multiple Conditions
function UserProfile({isLoggedIn, isPremium}) {
  return (
    <div>
      {isLoggedIn && <h2>Welcome User</h2>}
      {isPremium && <span>⭐ Premium Member</span>}
    </div>
  );
}

// With Variables
function Cart({items}) {
  const hasItems = items.length > 0;
  return (
    <div>
      {hasItems && <p>You have {items.length} items</p>}
    </div>
  );
}

Output (when hasMessages = true):

You have new messages!

🔹 If Statement Before Return

For complex conditions, use regular if statements before the return statement. This keeps your JSX clean and makes the logic easier to read and maintain.

// Early Return Pattern
function UserGreeting({user}) {
  if (!user) {
    return <p>Please log in</p>;
  }
  
  return <h1>Welcome, {user.name}!</h1>;
}

// Multiple Conditions
function StatusMessage({status}) {
  if (status === 'loading') {
    return <p>Loading...</p>;
  }
  
  if (status === 'error') {
    return <p>Error occurred!</p>;
  }
  
  return <p>Success!</p>;
}

// With Variable Assignment
function ProductCard({product}) {
  let badge;
  
  if (product.isNew) {
    badge = <span>New!</span>;
  } else if (product.onSale) {
    badge = <span>Sale!</span>;
  }
  
  return (
    <div>
      <h3>{product.name}</h3>
      {badge}
    </div>
  );
}

Output (when user exists):

Welcome, John!

🔹 Element Variables

Store JSX elements in variables using if statements, then render the variable. This approach separates logic from JSX, making components more readable and easier to test.

// Element Variable Pattern
function LoginControl({isLoggedIn}) {
  let button;
  
  if (isLoggedIn) {
    button = <button>Logout</button>;
  } else {
    button = <button>Login</button>;
  }
  
  return (
    <div>
      <h1>Welcome</h1>
      {button}
    </div>
  );
}

// Multiple Element Variables
function Dashboard({user}) {
  let header;
  let content;
  
  if (user.isAdmin) {
    header = <h1>Admin Dashboard</h1>;
    content = <AdminPanel />;
  } else {
    header = <h1>User Dashboard</h1>;
    content = <UserPanel />;
  }
  
  return (
    <div>
      {header}
      {content}
    </div>
  );
}

Output (when isLoggedIn = false):

Welcome

🔹 Switch Statement

Use switch statements for multiple conditions based on a single value. This is cleaner than multiple if-else statements when you have many possible cases to handle.

// Switch Statement Pattern
function StatusIcon({status}) {
  let icon;
  
  switch(status) {
    case 'success':
      icon = <span>✅</span>;
      break;
    case 'error':
      icon = <span>❌</span>;
      break;
    case 'warning':
      icon = <span>âš ī¸</span>;
      break;
    default:
      icon = <span>â„šī¸</span>;
  }
  
  return <div>{icon}</div>;
}

// Switch with Components
function PageContent({page}) {
  switch(page) {
    case 'home':
      return <HomePage />;
    case 'about':
      return <AboutPage />;
    case 'contact':
      return <ContactPage />;
    default:
      return <NotFoundPage />;
  }
}

Output (when status = 'success'):

✅

🔹 Null Rendering

Return null from a component to render nothing. This is useful when you want a component to exist in the tree but not display anything based on certain conditions.

// Render Nothing
function WarningBanner({show}) {
  if (!show) {
    return null;
  }
  
  return (
    <div className="warning">
      <p>Warning: Please check your input!</p>
    </div>
  );
}

// Conditional Null
function ErrorMessage({error}) {
  return error ? (
    <div className="error">{error}</div>
  ) : null;
}

// Using in Parent
function App() {
  const [showWarning, setShowWarning] = useState(false);
  
  return (
    <div>
      <h1>My App</h1>
      <WarningBanner show={showWarning} />
    </div>
  );
}

🔹 Inline If with Logical Operators

Combine multiple conditions using logical operators for more complex conditional rendering. This allows you to check multiple criteria before rendering elements in your components.

// Multiple Conditions with &&
function UserCard({user, isOnline, isPremium}) {
  return (
    <div>
      <h2>{user.name}</h2>
      {isOnline && isPremium && (
        <span>🌟 Premium Online</span>
      )}
    </div>
  );
}

// OR Operator
function Message({primaryMsg, fallbackMsg}) {
  return <p>{primaryMsg || fallbackMsg || 'No message'}</p>;
}

// Complex Conditions
function AccessControl({user}) {
  const canEdit = user.isAdmin || user.isOwner;
  const canDelete = user.isAdmin;
  
  return (
    <div>
      {canEdit && <button>Edit</button>}
      {canDelete && <button>Delete</button>}
    </div>
  );
}

Output (when isOnline and isPremium are true):

John Doe

🌟 Premium Online

🧠 Test Your Knowledge

Which operator is used for simple if-else in JSX?