← Back to Chapters

React Ternary Operator

⚛️ React Ternary Operator (JSX)

JSX Conditional Rendering   ? : Operator

? Quick Overview

The ternary operator (? :) is a compact way to perform conditional rendering in React JSX. It behaves like an inline if-else and is ideal when you want to toggle between two UI outputs directly inside JSX.

General syntax:

condition ? expressionIfTrue : expressionIfFalse

If condition is true, React evaluates and renders expressionIfTrue, otherwise it renders expressionIfFalse.

? Key Concepts

  • The ternary operator is a single expression that chooses between two values or JSX trees.
  • It is commonly used for inline UI decisions like switching labels, buttons, or views.
  • Both branches of the ternary must return a valid value (e.g., JSX, string, number, component).
  • For more complex conditions, avoid deep nesting to keep code readable.

? Syntax & Theory

Basic form in JavaScript:

// Returns valueA when condition is true, otherwise valueB
condition ? valueA : valueB

In React JSX:

  • You can use the ternary operator inside { } in JSX.
  • Each branch usually returns a JSX element or component.
  • When logic grows too big, move it into helper functions or variables.

? Basic JSX Example

Use a ternary to decide whether to show a Login or Logout button based on isLoggedIn.

? View Code Example
// Conditionally render Login or Logout button
function LoginButton({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? (
<button className="btn btn-danger">Logout</button>
) : (
<button className="btn btn-primary">Login</button>
)}
</div>
);
}

? Explanation

If isLoggedIn is true, React renders the red Logout button. If it is false, it renders the blue Login button instead.

? Rendering Text or Elements

You can use the ternary operator for simple text messages or full JSX content based on a value like user.

? View Code Example
// Show personalized greeting when user is present
function Greeting({ user }) {
return (
<h4>
{user ? `Welcome, ${user}! ?` : "Welcome, Guest!"}
</h4>
);
}

? Explanation

  • If user has a value (like "Alex"), the greeting becomes Welcome, Alex! ?.
  • If user is null or undefined, React shows "Welcome, Guest!".

? Conditional Component Rendering

Use ternaries to switch between entire components, such as admin and user views.

? View Code Example
// Swap whole components based on isAdmin flag
function AdminPanel() {
return <h5 className="text-danger">Admin Panel</h5>;
}

function UserPanel() {
return <h5 className="text-success">User Panel</h5>;
}

function Dashboard({ isAdmin }) {
return <div>{isAdmin ? <AdminPanel /> : <UserPanel />}</div>;
}

? Explanation

When isAdmin is true, the admin view is rendered; otherwise, the user view appears. This is common in dashboards, role-based views, and login-protected sections.

? Nested Ternary Operators

Nested ternaries allow multiple states (like loading, error, success), but they must be used carefully to avoid confusing code.

? View Code Example
// Handle loading, error and success states with nested ternary
function StatusIndicator({ status }) {
return (
<p>
{status === "loading"
? "⏳ Loading..."
: status === "error"
? "❌ Error occurred!"
: "✅ Success!"}
</p>
);
}

? Explanation

  • "loading" ⟶ shows ⏳ Loading...
  • "error" ⟶ shows ❌ Error occurred!
  • Any other value ⟶ shows ✅ Success!

If conditions grow more complex, move this logic into a separate function or replace with a clean if-else chain.

? Ternary vs Logical AND (&&)

Use ternary when you need to choose between two alternatives. Use && when you only want to conditionally render something when the condition is true.

? View Code Example
// Compare logical AND and ternary in JSX
// Using &&
{isAdmin && <p>You are an Admin</p>}

// Using ternary
{isAdmin ? <p>Welcome Admin</p> : <p>Welcome User</p>}

? Explanation

  • isAdmin && <p>You are an Admin</p> only renders the paragraph when isAdmin is true.
  • The ternary always renders exactly one branch: either “Welcome Admin” or “Welcome User”.

⚙️ Styling with Ternary

Ternaries can dynamically pick classes, inline styles, or labels for theming and mode switches.

? View Code Example
// Toggle theme styles and label with a ternary
function ThemeSwitcher({ darkMode }) {
return (
<div
className={darkMode ? "bg-dark text-light p-3" : "bg-light text-dark p-3"}
>
{darkMode ? "? Dark Mode" : "☀️ Light Mode"}
</div>
);
}

? Explanation

The container switches both its classes and label based on the value of darkMode, which is a common pattern in theme toggles and mode banners.

? Tips & Best Practices

  • Use ternaries for short, clear conditional expressions in JSX.
  • Prefer readability over brevity—when nesting, consider extracting logic into helper functions.
  • Wrap complex JSX inside parentheses ( ) for each branch to keep structure clear.
  • Ensure both the true and false branches return valid JSX or values.
  • If you see more than one nested ternary, consider refactoring to if-else or a separate component.

? Try It Yourself / Practice Tasks

  1. Build a LoginStatus component that toggles between “Login” and “Logout” buttons using a ternary on isLoggedIn.
  2. Create a ThemeCard component that switches between dark and light UI using ternary-based CSS classes.
  3. Implement a StatusMessage component that shows a loading spinner, success message, or error text using a nested ternary based on a status prop.
  4. Take one of your ternary-heavy components and rewrite it using if-else logic. Compare which version is easier to read.

Goal: Become comfortable using the ternary (? :) operator to render clear, concise, and efficient React JSX for alternative UI states.