Conditional Expressions in JSX – Detailed React JS Notes
Conditional Expressions in JSX allow developers to display different content, elements, or components based on a condition. They are commonly used to show login or logout buttons, display success or error messages, show product availability, manage loading states, and create interactive user interfaces.
React uses standard JavaScript conditional logic, including the ternary operator (? :), logical AND (&&), logical OR (||), and if...else statements. The best approach depends on whether you want to display one of two alternatives, show something conditionally, or choose between more complex UI structures. Read the official React guide to conditional rendering.
1. What Are Conditional Expressions in JSX?
Conditional expressions in JSX are JavaScript expressions used to determine what content React should render based on a condition.
Example:
function App() {
const isLoggedIn = true;
return (
<div>
{isLoggedIn ? (
<h1>Welcome Back!</h1>
) : (
<h1>Please Log In</h1>
)}
</div>
);
}
export default App;
Explanation:
isLoggedIn stores a Boolean value.
- The ternary operator checks whether the value is true or false.
- If true, React displays "Welcome Back!".
- If false, React displays "Please Log In".
Conditional rendering is useful when the UI must respond to a user's actions, application data, component props, or state.
2. Why Are Conditional Expressions Used in React?
Conditional expressions help developers build dynamic interfaces without creating separate pages for every possible situation.
- Authentication: Show login or logout options based on the user's status.
- Form validation: Display error messages when input is invalid.
- Loading states: Show a loading message while data is being fetched.
- Product availability: Display "In Stock" or "Out of Stock".
- User permissions: Show particular features to authorized users.
- Notifications: Display alerts only when necessary.
- Data display: Show a message when a list is empty.
- Responsive interactions: Change UI content according to state or props.
3. Conditional Expressions Using the Ternary Operator (? :)
The ternary operator is one of the most commonly used techniques for conditional rendering in JSX. It evaluates a condition and selects one of two expressions.
Syntax:
condition ? expressionIfTrue : expressionIfFalse
Inside JSX, use curly braces to include the expression.
{condition ? <ElementA /> : <ElementB />}
Example:
function App() {
const isStudent = true;
return (
<div>
{isStudent
? <p>You are a student.</p>
: <p>You are not a student.</p>}
</div>
);
}
How it works:
- If
isStudent is true, the first paragraph is rendered.
- If
isStudent is false, the second paragraph is rendered.
When to use: Use the ternary operator when you need to choose between two alternatives.
4. Ternary Operator with Text
You can use the ternary operator to change text inside an existing JSX element.
function App() {
const isLoggedIn = false;
return (
<div>
<h1>{isLoggedIn ? "Welcome User" : "Please Sign In"}</h1>
</div>
);
}
If isLoggedIn is false, the heading displays "Please Sign In".
Practical applications:
- Show "Login" or "Logout".
- Show "Available" or "Unavailable".
- Show "Pass" or "Fail".
- Show "Online" or "Offline".
5. Ternary Operator with CSS Classes
You can conditionally assign CSS classes to change the appearance of an element.
function Status() {
const isOnline = true;
return (
<p className={isOnline ? "online" : "offline"}>
{isOnline ? "User is Online" : "User is Offline"}
</p>
);
}
Corresponding CSS:
.online {
color: green;
}
.offline {
color: red;
}
When isOnline is true, the element receives the online class. Otherwise, it receives the offline class.
6. Conditional Rendering Using the Logical AND Operator (&&)
The logical AND operator is useful when you want to display an element only if a condition is true. If the condition is false, the expression does not display the intended JSX element.
Syntax:
{condition && <Element />}
Example:
function App() {
const showMessage = true;
return (
<div>
<h1>Dashboard</h1>
{showMessage && <p>Your profile has been updated successfully.</p>}
</div>
);
}
Explanation:
- If
showMessage is true, the paragraph is displayed.
- If
showMessage is false, React skips the paragraph.
When to use: Use && when there is only one optional element and you do not need an alternative in the false case.
Example: Showing a Notification
function Notification() {
const hasNotification = true;
return (
<div>
{hasNotification && (
<p>You have a new notification!</p>
)}
</div>
);
}
7. Important Warning When Using the Logical AND Operator
One common mistake is placing a number directly on the left side of &&. In JavaScript, 0 is falsy, but React can render the number zero as visible text.
Incorrect example:
function App() {
const messageCount = 0;
return (
<div>
{messageCount && <p>You have new messages.</p>}
</div>
);
}
This can display 0 on the page instead of displaying nothing.
Correct example:
function App() {
const messageCount = 0;
return (
<div>
{messageCount > 0 && (
<p>You have new messages.</p>
)}
</div>
);
}
Now the condition evaluates to a Boolean value. Since the count is zero, the paragraph is not rendered.
Remember: When using && for numeric values, compare the number explicitly, such as count > 0.
8. Conditional Rendering Using the Logical OR Operator (||)
The logical OR operator can provide a fallback value when the left-hand expression is falsy. It returns the left-hand value if it is truthy; otherwise, it returns the right-hand value.
Example:
function App() {
const userName = "";
return (
<div>
<h1>Welcome, {userName || "Guest"}!</h1>
</div>
);
}
Because userName is an empty string, the heading displays "Welcome, Guest!".
Important: The || operator treats values such as 0, false, and an empty string as falsy. If zero or false is a valid value that should be preserved, consider using the nullish coalescing operator (??) instead.
9. Conditional Rendering Using the Nullish Coalescing Operator (??)
The nullish coalescing operator provides a fallback only when the left-hand value is null or undefined. It does not replace valid values such as zero, false, or an empty string.
function App() {
const score = 0;
const userName = null;
return (
<div>
<p>Score: {score ?? "Not Available"}</p>
<p>Name: {userName ?? "Guest"}</p>
</div>
);
}
The output displays a score of zero and the fallback name "Guest".
Difference between || and ??:
| Value |
value || "Fallback" |
value ?? "Fallback" |
0 |
Fallback |
0 |
false |
Fallback |
false |
"" |
Fallback |
Empty string |
null |
Fallback |
Fallback |
undefined |
Fallback |
Fallback |
10. Conditional Rendering Using if...else Statements
JavaScript if...else statements are useful when the rendering logic is more complex. You cannot place an ordinary if...else statement directly inside a JSX expression, but you can use it before the return statement or to assign JSX to a variable.
Example:
function App() {
const isLoggedIn = true;
if (isLoggedIn) {
return <h1>Welcome Back!</h1>;
} else {
return <h1>Please Log In</h1>;
}
}
If isLoggedIn is true, the component returns the welcome heading. Otherwise, it returns the login message.
Example Using a Variable
function App() {
const isAdmin = false;
let content;
if (isAdmin) {
content = <h2>Admin Dashboard</h2>;
} else {
content = <h2>User Dashboard</h2>;
}
return (
<div>
<h1>Dashboard</h1>
{content}
</div>
);
}
When to use: Prefer if...else when conditions involve multiple steps, multiple branches, or complex calculations.
11. Conditional Rendering Using Early Returns
An early return allows a component to return a particular result before reaching its main JSX. It can make loading, error, and authentication logic easier to understand.
function Profile({ isLoading, hasError, user }) {
if (isLoading) {
return <p>Loading profile...</p>;
}
if (hasError) {
return <p>Unable to load profile.</p>;
}
if (!user) {
return <p>User not found.</p>;
}
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
This component handles the loading, error, missing-user, and success cases separately. Early returns can prevent deeply nested conditional expressions.
12. Returning null to Render Nothing
A React component can return null when it should not display any UI.
function Warning({ shouldShow }) {
if (!shouldShow) {
return null;
}
return <p>Please check your information before continuing.</p>;
}
If shouldShow is false, the component renders nothing.
This pattern is useful for optional alerts, hidden panels, and elements that should not appear under certain conditions.
13. Nested Ternary Expressions
A nested ternary expression is a ternary operator placed inside another ternary operator. It can handle more than two outcomes, but excessive nesting can make code difficult to read.
function App() {
const score = 75;
return (
<div>
<h2>
{score >= 90
? "Grade A"
: score >= 70
? "Grade B"
: score >= 50
? "Grade C"
: "Needs Improvement"}
</h2>
</div>
);
}
With a score of 75, the output is "Grade B".
Best practice: Use nested ternaries sparingly. If the condition has many branches, use if...else if...else, a lookup object, or a separate component for improved readability.
14. Conditional Expressions in JSX Attributes
Conditional expressions can also determine attribute values, including CSS classes, button states, and image sources.
14.1 Conditional Button State
function SubmitButton({ isSubmitting }) {
return (
<button disabled={isSubmitting}>
{isSubmitting ? "Submitting..." : "Submit"}
</button>
);
}
The button is disabled while submission is in progress, and its text changes accordingly.
14.2 Conditional Image Source
function Avatar({ isPremium }) {
const imageUrl = isPremium
? "/images/premium-avatar.png"
: "/images/default-avatar.png";
return <img src={imageUrl} alt="User avatar" />;
}
The displayed image depends on whether the user has premium status.
14.3 Conditional CSS Class
function Alert({ isError, message }) {
return (
<div className={isError ? "alert error" : "alert success"}>
{message}
</div>
);
}
This example applies a different CSS class based on the value of isError.
15. Conditional Rendering Based on Props
Props allow a parent component to pass information to a child component. The child can use those values to decide what to render.
function Greeting({ isLoggedIn, name }) {
return (
<div>
{isLoggedIn ? (
<h1>Welcome, {name}!</h1>
) : (
<h1>Please sign in to continue.</h1>
)}
</div>
);
}
function App() {
return (
<div>
<Greeting isLoggedIn={true} name="Priya" />
<Greeting isLoggedIn={false} name="Aarav" />
</div>
);
}
The first component instance displays a personalized welcome message, while the second displays the sign-in message.
16. Conditional Rendering Based on State
React state stores information that can change over time. When state changes, React can render the UI again to reflect the new value.
import { useState } from "react";
function ToggleMessage() {
const [isVisible, setIsVisible] = useState(false);
return (
<div>
<button onClick={() => setIsVisible(!isVisible)}>
{isVisible ? "Hide Message" : "Show Message"}
</button>
{isVisible && (
<p>This message appears when you click the button.</p>
)}
</div>
);
}
export default ToggleMessage;
How it works:
useState(false) initializes the message as hidden.
- The button updates the state when clicked.
- The button text changes depending on the state.
- The paragraph appears only when
isVisible is true.
This is a practical example of conditional rendering in an interactive React component.
17. Practical Example: Product Availability
This example uses conditional expressions to display a product's availability and control the purchase button.
function ProductCard() {
const product = {
name: "Wireless Headphones",
price: 1999,
inStock: true
};
return (
<div className="product-card">
<h2>{product.name}</h2>
<p>Price: ₹{product.price}</p>
<p>
{product.inStock ? "In Stock" : "Out of Stock"}
</p>
{product.inStock && (
<p>Available for immediate purchase.</p>
)}
<button disabled={!product.inStock}>
{product.inStock ? "Buy Now" : "Unavailable"}
</button>
</div>
);
}
export default ProductCard;
Concepts demonstrated:
- Ternary operator for choosing text.
- Logical AND for optional content.
- Boolean expression for the disabled attribute.
- JavaScript object properties inside JSX.
18. Comparison of Conditional Rendering Techniques
| Technique |
Purpose |
Example |
Best Use |
| Ternary operator |
Choose between two alternatives. |
{isOpen ? "Open" : "Closed"} |
Two possible outcomes. |
| Logical AND |
Render content when a condition is true. |
{show && } |
Optional content. |
| Logical OR |
Provide a fallback for falsy values. |
{name || "Guest"} |
Fallback values when falsy values should trigger the fallback. |
| Nullish coalescing |
Provide a fallback for null or undefined. |
{count ?? "Unknown"} |
Preserving values such as zero or false. |
| if...else |
Choose between blocks of logic. |
if (isAdmin) { ... } |
Complex or multi-step conditions. |
| Early return |
Return early for specific UI states. |
if (loading) return Loading... ; |
Loading, errors, or missing data. |
| Return null |
Render no UI from a component. |
if (!visible) return null; |
Completely hidden content. |
19. Common Mistakes in Conditional Expressions
| Incorrect Approach |
Correct Approach |
Reason |
{isLoggedIn ? "Welcome"} |
{isLoggedIn ? "Welcome" : "Please log in"} |
A ternary expression requires both the true and false expressions. |
{count && Messages } |
{count > 0 && Messages } |
A zero count can render the number zero. |
{if (isReady) ...} |
Use a ternary expression or an if statement outside JSX. |
An ordinary if statement is not a JSX expression. |
{name || "Guest"} when zero must be preserved |
{name ?? "Guest"} |
Logical OR treats zero as falsy. |
| Using many nested ternaries |
Use clear if...else logic or separate components. |
Deep nesting reduces readability. |
Using isReady = true inside a condition |
Use isReady === true for comparison when needed. |
A single equals sign assigns a value rather than comparing values. |
Using a Boolean string such as "false" |
Use an actual Boolean value such as false. |
Non-empty strings are truthy in JavaScript. |
20. Best Practices for Conditional Expressions in JSX
- Use the ternary operator for simple two-way decisions.
- Use
&& when you want to render optional content only when a condition is true.
- Compare numeric values explicitly before using them with
&&.
- Use
|| when any falsy value should trigger a fallback.
- Use
?? when only null or undefined should trigger a fallback.
- Use
if...else or early returns for complex rendering logic.
- Keep nested ternaries to a minimum.
- Use descriptive variable names such as
isLoading, hasError, and isLoggedIn.
- Keep conditions readable and separate complicated calculations from JSX where appropriate.
- Test both true and false cases to verify the expected UI.
- Do not treat hiding a UI element as a substitute for server-side authorization or security checks.
21. Interview Questions and Answers
Q1. What are conditional expressions in JSX?
They are JavaScript expressions used inside JSX to decide which text, element, or component should be displayed based on a condition.
Q2. What is the ternary operator?
The ternary operator uses the syntax condition ? expressionIfTrue : expressionIfFalse to select one of two expressions.
Q3. What is the purpose of the logical AND operator in JSX?
The && operator is commonly used to render an element only when a condition is true.
Q4. Why can using count && in JSX display zero?
JavaScript's logical AND operator returns the original falsy value when the left side is falsy. If that value is zero, React can display zero as text.
Q5. Can we use if...else directly inside JSX?
No. An ordinary if...else statement cannot be inserted directly inside a JSX expression. Use it before the return statement, assign its result to a variable, or use a ternary expression inside JSX.
Q6. What is the difference between || and ???
The || operator uses the fallback for any falsy left-hand value, while ?? uses the fallback only for null or undefined.
Q7. What does returning null do in a React component?
Returning null means the component renders no visible UI.
Q8. How do you conditionally change a button's text?
Use a ternary expression inside the button, for example, {isSaving ? "Saving..." : "Save"}.
Q9. How can state control conditional rendering?
State stores a value that can change over time. When the state changes, React renders the component again and updates the UI based on the new value.
Q10. Which conditional technique should be used for complex logic?
Use if...else, early returns, a lookup object, or separate components when complex conditions would make inline expressions difficult to read.
22. Quick Revision Checklist
- Understand conditional rendering in React.
- Know the syntax of the ternary operator.
- Understand the logical AND operator and its zero-value pitfall.
- Know how logical OR provides fallback values.
- Understand nullish coalescing.
- Use
if...else and early returns for complex logic.
- Know how to return
null when nothing should be rendered.
- Apply conditions to text, CSS classes, attributes, and components.
- Practice conditional rendering with props and state.
- Test all possible condition outcomes.
23. Conclusion
Conditional expressions in JSX are essential for creating dynamic React applications. They allow developers to change content based on user authentication, application state, props, validation results, and other conditions. The ternary operator is ideal for two alternatives, && is useful for optional content, and if...else or early returns work well for more complex logic.
Practicing these techniques will help you build interactive dashboards, forms, product cards, notifications, authentication interfaces, and other real-world React applications.
Useful React JS Training Links