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

Nesting Ternaries: When It's Acceptable

Shallow nesting with clear formatting can work, but deeper nesting usually signals refactoring is needed.

Nesting Ternaries: When It's Acceptable

You'll learn: When shallow ternary nesting enhances clarity and when it becomes a code smell requiring refactoring.

Nesting ternaries means placing one ternary operator inside another. You've seen single ternaries for if-else logic in JSX — sometimes you need multiple conditions. The key question: does nesting make your intent clearer or obscure it?

The One-Level Nesting Sweet Spot

Shallow nesting with careful formatting can actually improve readability when you have a clear three-way branch:

// Acceptable: One level, well-formatted
<div>
  {status === 'loading' 
    ? <Spinner /> 
    : status === 'error'
      ? <ErrorMessage />
      : <DataDisplay />}
</div>

This reads like "if loading, show spinner; else if error, show error; else show data." The indentation creates visual hierarchy.

When Nesting Goes Wrong

Beyond one level, or without clear formatting, ternaries become unreadable:

// Unreadable: Too deep
{a ? b ? c ? d : e : f : g}

This signals you need refactoring: extract logic to variables, use multiple && checks, or create a helper function.

The Formatting Rule

If your nested ternary fits these criteria, it's acceptable:

  • One level deep maximum
  • Each branch on its own line
  • Clear indentation showing the decision tree
  • Obvious what each condition tests

Think of it like a simple flowchart: one decision, then one sub-decision. Anything more complex deserves its own function outside JSX.

Key Takeaway: One level of ternary nesting with clear formatting can improve clarity for three-way branches, but deeper nesting always means it's time to refactor into variables or functions.