Course contentsShow
← React
Lesson 120 of 2,3964. Conditional Rendering in JSXFree lesson

Inline Ternaries for Component Selection

Conditionally render entirely different components: {isLoggedIn ? <Dashboard /> : <LoginForm />}.

Inline Ternaries for Component Selection

What you'll learn: How to use ternary operators to choose between entirely different components in JSX based on a condition.


The Core Idea

You already know ternaries can pick between simple values or elements. But they become truly powerful when choosing between complete components. Instead of showing different text or a single element, you can render an entirely different UI structure—like showing a full dashboard for logged-in users versus a login form for guests.

The pattern looks like this:

{isLoggedIn ? <Dashboard /> : <LoginForm />}

This is a binary choice: one component or the other, never both, never neither.


When This Pattern Shines

This technique excels when:

  • You have two distinct UIs for the same screen (authenticated vs unauthenticated)
  • The condition is clearly binary (yes/no, loaded/loading, success/error)
  • Both components are self-contained and don't need to share rendered structure

Example:

function App() {
  const userLoggedIn = true;
  
  return (
    <div>
      <header>My App</header>
      {userLoggedIn ? <Dashboard /> : <LoginForm />}
    </div>
  );
}

When userLoggedIn is true, React renders <Dashboard />. When false, <LoginForm /> appears instead. The components can be completely different—different props, different child components, different complexity.


Think of It Like a Doorway

Imagine a doorway with two rooms behind it. The ternary is the door that opens to exactly one room based on your access badge (the condition). You never see both rooms simultaneously.


Key Takeaway: Use inline ternaries with component tags to create clean, binary UI switches—when you need to render one complete component or another based on a single condition.