The ternary operator is a JavaScript operator that allows you to choose between two values based on a condition.
It is especially useful in React because JSX allows JavaScript expressions inside curly braces.
For example:
const isLoggedIn = true;
return (
<div>
{isLoggedIn ? <h2>Welcome Back!</h2> : <h2>Please Log In</h2>}
</div>
);
If isLoggedIn is true, React renders:
Welcome Back!
If it is false, React renders:
Please Log In
The ternary operator is one of the most common ways to handle simple conditional UI in React.
What Is the Ternary Operator?
The ternary operator is a shorthand way of writing a simple if...else condition.
Its basic JavaScript syntax is:
condition ? valueIfTrue : valueIfFalse
It has three parts:
condition
?
value if true
:
value if false
For example:
const age = 20;
const message = age >= 18
? "Adult"
: "Minor";
The condition is:
age >= 18
If the condition is true, the result is:
Adult
Otherwise:
Minor
Why Is It Called a Ternary Operator?
The word ternary means something involving three parts.
The ternary operator has three operands:
condition
true result
false result
For example:
isOnline ? "Online" : "Offline"
The three parts are:
isOnline
"Online"
"Offline"
The ? separates the condition from the true result.
The : separates the true result from the false result.
Ternary Operator vs if...else
The same logic can be written using if...else.
Using if...else:
let message;
if (isLoggedIn) {
message = "Welcome";
} else {
message = "Please log in";
}
Using the ternary operator:
const message = isLoggedIn
? "Welcome"
: "Please log in";
The ternary version is shorter and can be used directly as an expression.
This is particularly useful inside JSX.
Using the Ternary Operator in JSX
React allows JavaScript expressions inside {}.
Therefore, you can use a ternary directly inside JSX:
function App() {
const isLoggedIn = true;
return (
<div>
{isLoggedIn ? <h2>Dashboard</h2> : <h2>Login</h2>}
</div>
);
}
The expression:
isLoggedIn ? <h2>Dashboard</h2> : <h2>Login</h2>
is evaluated by JavaScript.
React then renders the JSX returned by that expression.
Ternary With Text
You do not have to return JSX elements.
A ternary can return simple text:
const isOnline = true;
<p>
{isOnline ? "Online" : "Offline"}
</p>
Another example:
const isPremium = false;
<p>
{isPremium ? "Premium Member" : "Free Member"}
</p>
This is useful when only the displayed text needs to change.
Ternary With Numbers
A ternary can also return numbers.
const isDiscounted = true;
const price = isDiscounted ? 799 : 999;
You can display the result:
<p>
Price: ₹{isDiscounted ? 799 : 999}
</p>
If the product is discounted, React displays:
Price: ₹799
Otherwise:
Price: ₹999
Ternary With Variables
You can use variables as the true and false results.
const isDarkMode = true;
const theme = isDarkMode
? "dark"
: "light";
Then:
<div className={theme}>
Website Content
</div>
This is useful when the result is used in several places.
Ternary With className
A very common React use case is changing a CSS class based on a condition.
const isActive = true;
<button
className={isActive ? "button active" : "button"}
>
Profile
</button>
When isActive is true:
button active
When it is false:
button
This allows your UI to visually respond to application state.
Ternary With style
The ternary operator can also control inline styles.
const isActive = true;
<div
style={{
color: isActive ? "blue" : "gray"
}}
>
Profile
</div>
You can conditionally change several style values:
<button
style={{
backgroundColor: isActive ? "blue" : "gray",
color: "white",
cursor: isActive ? "pointer" : "default"
}}
>
Profile
</button>
Ternary With React Components
The true and false results can be complete React components.
function App() {
const isLoggedIn = true;
return (
<>
{isLoggedIn ? <Dashboard /> : <Login />}
</>
);
}
This is one of the most common patterns in React.
The application chooses which component to render based on the current state.
Ternary With Props
Props can be used as conditions.
function UserStatus({ isOnline }) {
return (
<p>
{isOnline ? "User is online" : "User is offline"}
</p>
);
}
Use it like:
<UserStatus isOnline={true} />
or:
<UserStatus isOnline={false} />
The component’s output changes according to the prop.
Ternary With State
The ternary operator becomes especially useful when combined with React state.
import { useState } from "react";
function Toggle() {
const [isVisible, setIsVisible] = useState(false);
return (
<div>
<button onClick={() => setIsVisible(!isVisible)}>
{isVisible ? "Hide" : "Show"}
</button>
{isVisible ? (
<p>
This content is visible.
</p>
) : (
<p>
This content is hidden.
</p>
)}
</div>
);
}
The button text changes depending on the state.
When:
isVisible = true
the button displays:
Hide
When:
isVisible = false
it displays:
Show
Ternary for Login and Logout
Authentication interfaces are a common example.
function Header({ isLoggedIn }) {
return (
<header>
{isLoggedIn ? (
<button>Logout</button>
) : (
<button>Login</button>
)}
</header>
);
}
The same component displays the appropriate action based on the user’s authentication state.
Ternary for Loading States
You can use a ternary to display a loading message.
function UserList({ loading, users }) {
return (
<div>
{loading ? (
<p>Loading users...</p>
) : (
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name}
</li>
))}
</ul>
)}
</div>
);
}
When loading is true, the loading message appears.
When it is false, the user list appears.
Ternary for Empty States
You can check whether an array contains data.
function CourseList({ courses }) {
return (
<div>
{courses.length > 0 ? (
<ul>
{courses.map((course) => (
<li key={course.id}>
{course.name}
</li>
))}
</ul>
) : (
<p>No courses available.</p>
)}
</div>
);
}
This is a common pattern for applications that display data from APIs or databases.
Ternary for Buttons
Buttons often change their text based on state.
const isSaved = true;
<button>
{isSaved ? "Saved" : "Save"}
</button>
You can also change the action:
<button
onClick={
isSaved
? handleRemove
: handleSave
}
>
{isSaved ? "Remove" : "Save"}
</button>
Now both the button text and its behavior can depend on the state.
Ternary With Multiple JSX Elements
The true or false side of a ternary can contain multiple elements.
Wrap them in a Fragment or another parent element.
{isLoggedIn ? (
<>
<h2>Welcome Back</h2>
<p>You are logged in.</p>
<button>Logout</button>
</>
) : (
<>
<h2>Welcome</h2>
<p>Please log in to continue.</p>
<button>Login</button>
</>
)}
This is useful when each condition needs to display an entire group of elements.
Ternary With Functions
You can use a function to determine the condition.
function isAdult(age) {
return age >= 18;
}
Then:
const age = 20;
<p>
{isAdult(age) ? "Adult" : "Minor"}
</p>
The function returns a boolean, which becomes the condition for the ternary operator.
Ternary With Object Data
Suppose you have a user object:
const user = {
name: "Arafat",
verified: true
};
You can conditionally display a badge:
<div>
<h2>{user.name}</h2>
{user.verified ? (
<span>Verified</span>
) : (
<span>Not Verified</span>
)}
</div>
This pattern is useful for displaying badges, account states, product states, and other data-driven UI.
Nested Ternary Operators
A ternary can contain another ternary.
For example:
const status = "success";
<p>
{status === "loading"
? "Loading..."
: status === "success"
? "Success!"
: "Something went wrong."}
</p>
This works, but nested ternaries can become difficult to read.
A small amount of nesting may be acceptable, but if the logic becomes complicated, another approach is usually better.
Avoid Deeply Nested Ternaries
Consider:
{status === "loading"
? "Loading..."
: status === "success"
? "Success"
: status === "error"
? "Error"
: status === "empty"
? "No Data"
: "Unknown"}
This technically works, but it becomes difficult to understand.
Instead, use if statements:
function getStatusMessage(status) {
if (status === "loading") {
return "Loading...";
}
if (status === "success") {
return "Success";
}
if (status === "error") {
return "Error";
}
if (status === "empty") {
return "No Data";
}
return "Unknown";
}
Then:
<p>{getStatusMessage(status)}</p>
The result is easier to read and maintain.
Ternary Operator and &&
Both ternary and && can perform conditional rendering, but they are useful in different situations.
Use a ternary when you have two possible outcomes:
{isLoggedIn ? <Dashboard /> : <Login />}
Use && when you only need to render something when the condition is true:
{isAdmin && <AdminPanel />}
Think of it like this:
Ternary
Condition
↓
TRUE → A
FALSE → B
&&
Condition
↓
TRUE → A
FALSE → nothing
Ternary Operator Outside JSX
The ternary operator is not specific to React.
It is a JavaScript feature.
For example:
const age = 25;
const category =
age >= 18
? "Adult"
: "Minor";
React simply makes it particularly useful because JavaScript expressions can be placed inside JSX.
For example:
<p>
{age >= 18 ? "Adult" : "Minor"}
</p>
So understanding the JavaScript ternary operator will help you beyond React as well.
Ternary Operator With Function Calls
The true and false results can call functions.
function login() {
console.log("Login");
}
function logout() {
console.log("Logout");
}
const isLoggedIn = true;
<button onClick={isLoggedIn ? logout : login}>
{isLoggedIn ? "Logout" : "Login"}
</button>
Notice that the functions are passed without parentheses:
logout
and:
login
You generally do not want to call them during rendering:
onClick={isLoggedIn ? logout() : login()}
That would execute the functions while rendering rather than when the button is clicked.
Ternary Operator With null
You can use null as one side of a ternary when you want to render nothing.
{isAdmin ? <AdminPanel /> : null}
If isAdmin is true, the panel appears.
If false, nothing is rendered.
However, when you only need to render something when true, && is often simpler:
{isAdmin && <AdminPanel />}
Ternary Operator With null for Optional Content
You can also use null when an optional component should not appear.
function Notification({ message }) {
return (
<div>
{message ? (
<p>{message}</p>
) : (
null
)}
</div>
);
}
For this particular example, && would generally be more concise:
{message && <p>{message}</p>}
Formatting Long Ternary Expressions
Long ternaries are easier to read when each branch is placed on separate lines.
Instead of:
{isLoggedIn ? <Dashboard /> : <Login />}
you can format a larger expression like this:
{isLoggedIn ? (
<Dashboard />
) : (
<Login />
)}
For multiple elements:
{isLoggedIn ? (
<>
<h2>Welcome Back</h2>
<Dashboard />
</>
) : (
<>
<h2>Please Log In</h2>
<Login />
</>
)}
Good formatting makes conditional JSX much easier to scan.
A Practical Example
Let’s create a course enrollment button.
function CourseButton({ enrolled, available }) {
if (!available) {
return (
<button disabled>
Course Unavailable
</button>
);
}
return (
<button>
{enrolled ? "Continue Learning" : "Enroll Now"}
</button>
);
}
The ternary:
enrolled
? "Continue Learning"
: "Enroll Now"
changes the button text.
If the student is already enrolled:
Continue Learning
Otherwise:
Enroll Now
The if statement handles the more important availability condition, while the ternary handles the simple two-option text change.
This is often a good way to combine different conditional techniques without making the JSX complicated.
Another Practical Example
Here is a user profile card:
function ProfileCard({ user }) {
return (
<div className="profile-card">
<h2>{user.name}</h2>
<p>
{user.isOnline ? "Online" : "Offline"}
</p>
<p>
{user.isPremium ? "Premium Member" : "Free Member"}
</p>
<button>
{user.isFollowing ? "Unfollow" : "Follow"}
</button>
</div>
);
}
Example data:
const user = {
name: "Arafat",
isOnline: true,
isPremium: false,
isFollowing: true
};
The component can dynamically display:
Arafat
Online
Free Member
Unfollow
All of these values are controlled by the object’s state.
Common Mistakes
Forgetting the :
A ternary requires both outcomes.
Incorrect:
{isLoggedIn ? <Dashboard />}
Correct:
{isLoggedIn ? <Dashboard /> : <Login />}
Using if Inside JSX
This is invalid:
<div>
{if (isLoggedIn) {
<Dashboard />;
}}
</div>
Use a ternary:
<div>
{isLoggedIn ? <Dashboard /> : <Login />}
</div>
or move the if outside the JSX.
Calling Functions Immediately
Be careful with event handlers:
<button onClick={isLoggedIn ? logout() : login()}>
Click
</button>
This can call the functions during rendering.
Instead:
<button onClick={isLoggedIn ? logout : login}>
Click
</button>
Overusing Nested Ternaries
Avoid creating huge conditional expressions:
condition1
? result1
: condition2
? result2
: condition3
? result3
: result4
If the logic is becoming difficult to read, move it into a function or use if statements.
Confusing Ternary With &&
If there is no false result:
{isAdmin && <AdminPanel />}
is often cleaner.
If there are two possible results:
{isAdmin ? <AdminPanel /> : <UserPanel />}
use a ternary.
Ternary Operator Cheat Sheet
| Situation | Example |
|---|---|
| Basic JavaScript | condition ? a : b |
| Conditional text | {isOnline ? "Online" : "Offline"} |
| Conditional component | {isAdmin ? <Admin /> : <User />} |
| Conditional class | className={active ? "active" : "inactive"} |
| Conditional style | color: active ? "blue" : "gray" |
| Conditional button text | {saved ? "Saved" : "Save"} |
| Conditional image | src={dark ? darkImg : lightImg} |
| Render nothing | {condition ? <Box /> : null} |
| Multiple JSX elements | {condition ? <>...</> : <>...</>} |
| Multiple conditions | Nested ternary, but use carefully |
Practice Exercise
Create a CourseCard component that receives:
const course = {
name: "React Fundamentals",
enrolled: false,
available: true,
premium: false
};
The component should display:
- The course name.
"Enroll Now"if the user is not enrolled."Continue Learning"if the user is enrolled."Available"when the course is available."Unavailable"when the course is not available."Premium Course"when the course is premium."Free Course"when the course is not premium.
Use the ternary operator for these conditions.
Then try changing:
enrolled: true
and observe how the UI changes.
Next, change:
available: false
and create a disabled button for the unavailable course.
Where to Place an Image
Place this image after the section “Ternary Operator vs if...else“.
Create a 16:9 React educational infographic showing the ternary operator visually:
CONDITION
│
┌────┴────┐
TRUE FALSE
│ │
▼ ▼
<Dashboard /> <Login />
isLoggedIn
? <Dashboard />
: <Login />
Use a polished modern React developer aesthetic, dark coding-editor background, clean JSX syntax highlighting, and a clear decision-tree layout.
Caption: Understanding the ternary operator in React
Alt text: Ternary operator decision tree showing different React components for true and false conditions
Key Takeaways
- The ternary operator is a JavaScript operator with three parts.
- Its basic syntax is
condition ? trueValue : falseValue. - It provides a concise way to express simple
if...elselogic. - Ternary expressions work particularly well inside JSX.
- You can use ternaries for text, numbers, components, classes, styles, attributes, and other values.
- Props and state are commonly used as ternary conditions in React.
- A ternary always provides a true result and a false result.
- Use
&&when you only need to render something when a condition is true. - Use
ifstatements when conditional logic becomes more complex. - Avoid deeply nested ternary expressions because they reduce readability.
- You can use
nullas a result when you want nothing rendered. - The ternary operator is a JavaScript feature, not a React-specific feature.
- Understanding ternaries is essential for writing clean conditional JSX.
The core pattern to remember is:
{condition ? <TrueContent /> : <FalseContent />}
React evaluates the condition and displays the appropriate result. Once you become comfortable with this pattern, many common UI decisions become much easier to express.