0
0
ReactHow-ToBeginner · 3 min read

How to Use Ternary Operator in JSX for Conditional Rendering

In JSX, you use the ternary operator inside curly braces to conditionally render elements: {condition ? trueValue : falseValue}. It works like a simple if-else that chooses what to show based on the condition.
📐

Syntax

The ternary operator in JSX follows this pattern:

  • condition: A JavaScript expression that evaluates to true or false.
  • trueValue: What JSX renders if the condition is true.
  • falseValue: What JSX renders if the condition is false.

Wrap the whole expression in curly braces {} to embed it inside JSX.

jsx
{condition ? trueValue : falseValue}
💻

Example

This example shows how to display a greeting message based on a isLoggedIn boolean. It uses the ternary operator to choose between two messages.

jsx
import React from 'react';

export default function Greeting() {
  const isLoggedIn = true;
  return (
    <div>
      {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>}
    </div>
  );
}
Output
<h1>Welcome back!</h1>
⚠️

Common Pitfalls

Common mistakes when using the ternary operator in JSX include:

  • Forgetting to wrap the expression in curly braces {}, so JSX treats it as plain text.
  • Not providing the falseValue part, which can cause syntax errors.
  • Using complex logic inside the ternary, making code hard to read; prefer simple conditions or extract logic outside JSX.
jsx
/* Wrong: missing curly braces */
// <div>isLoggedIn ? <h1>Hi</h1> : <h1>Bye</h1></div>

/* Right: with curly braces */
// <div>{isLoggedIn ? <h1>Hi</h1> : <h1>Bye</h1>}</div>
📊

Quick Reference

Use this quick guide when writing ternary operators in JSX:

PartDescriptionExample
conditionExpression that returns true or falseisLoggedIn
trueValueRendered if condition is true

Welcome back!

falseValueRendered if condition is false

Please sign up.

curly bracesWrap the whole ternary in JSX{condition ? trueValue : falseValue}

Key Takeaways

Always wrap the ternary operator expression in curly braces inside JSX.
Use the ternary operator to choose between two JSX elements based on a condition.
Provide both true and false parts to avoid syntax errors.
Keep ternary expressions simple for better readability.
Ternary operator is a concise alternative to if-else for conditional rendering in React.