The ternary operator is a simplified, one-line conditional statement. It is basically a shorthand way of writing an if...else block.
In React, you cannot use standard if statements directly inside JSX return blocks. Because of this restriction, the ternary operator is incredibly important—it is the standard way to perform conditional rendering in React.
The ternary operator takes three operands: a condition, a result for true, and a result for false.
condition ? <expression if true> : <expression if false>
if/else vs TernaryLet's look at a simple example to check if a user is authenticated.
Using standard if/else:
let authenticated = true; let message;if (authenticated) { message = "Welcome back!"; } else { message = "Please log in."; }
Using the Ternary Operator:
let authenticated = true; let message = authenticated ? "Welcome back!" : "Please log in.";
As you can see, the ternary operator is much more compact.
React allows you to embed JavaScript expressions inside JSX using curly braces {}. However, a standard if statement is not an expression, so it will cause a syntax error if placed inside JSX.
The ternary operator is an expression, making it perfect for JSX.
import React from 'react';const UserGreeting = ({ isLoggedIn }) => { return ( <div> {/* The ternary operator inside JSX */} {isLoggedIn ? <h1>Welcome back to your dashboard!</h1> : <h1>Please sign in to continue.</h1>} </div> ); };
export default UserGreeting;
In this example, if the isLoggedIn prop is true, it renders the welcome message. If false, it renders the sign-in prompt.
&&) AlternativeSometimes, you only want to render something if a condition is true, and render nothing if it's false. While you could use a ternary operator that returns null for the false condition, React developers often use the Logical AND (&&) operator instead.
Using Ternary:
{ unreadMessages.length > 0 ? <h2>You have unread messages!</h2> : null }
Using Logical AND (&&):
{ unreadMessages.length > 0 && <h2>You have unread messages!</h2> }
In JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false. React ignores false during rendering, so the element simply won't appear.
While ternary operators are fantastic, chaining too many of them together can make your code impossible to read.
// Avoid doing this! const result = a ? (b ? "yes" : "no") : (c ? "maybe" : "never");
If your logic is this complex, it is much better to handle the condition in a standard if/else block before the return statement in your React component, and then just return the resulting variable in the JSX.
condition ? true : false) is a short-hand for if/else.&&) operator is a cleaner alternative.Why is the ternary operator preferred over standard if statements inside React JSX?