Popular Searches
Popular Course Categories
Popular Courses

Logical AND and Ternary Rendering

Logical AND and Ternary Rendering

React Events and Conditional Rendering

Logical AND (&&) and Ternary Rendering in React JS

Logical AND (&&) and Ternary Rendering are important conditional rendering techniques in React JS. They allow developers to display, hide, or change UI elements based on conditions such as user login status, product availability, form validation, loading status, and notification counts.

React JS Training: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. What Is Conditional Rendering in React?

Conditional rendering means displaying different UI elements depending on whether a condition is true or false. React uses standard JavaScript operators and expressions to control which elements appear on the screen.

For example, an application may display a Welcome message when a user is logged in and a Login button when the user is logged out.

Common Conditional Rendering Techniques

  • Logical AND (&&): Displays an element when a condition is true; otherwise, it displays nothing.
  • Ternary Operator (condition ? trueValue : falseValue): Displays one result when a condition is true and another when it is false.
  • if/else: Uses JavaScript statements to handle more complex conditions.

2. What Is the Logical AND (&&) Operator?

The logical AND operator (&&) is a JavaScript operator that checks the left-hand condition. In React, it is commonly used to render JSX only when a condition is true or truthy.

Syntax

{'condition && expression'}

If the condition is true or truthy, JavaScript evaluates and returns the expression on the right. If the condition is false or falsy, JavaScript returns the left-hand value. React does not render boolean values such as false, but values such as 0 can appear on the screen.

Example 1: Display a Message

{'function App() {\n  const isLoggedIn = true;\n  return (\n    
\n {isLoggedIn &&

Welcome Back!

}\n
\n  );\n}\nexport default App;'}

Output: Welcome Back!

Explanation: Since isLoggedIn is true, React renders the heading. If isLoggedIn is false, the heading is not rendered.

Example 2: Show a Notification

{'function Notifications() {\n  const hasNotifications = true;\n  return (\n    
\n

Notifications

\n {hasNotifications &&

You have new notifications.

}\n
\n  );\n}\nexport default Notifications;'}

Output: The Notifications heading and the message appear when hasNotifications is true.

Example 3: Display an Unread Message Count

{'function MessageBox() {\n  const messageCount = 5;\n  return (\n    
\n

Inbox

\n {messageCount > 0 && (\n

You have {messageCount} unread messages.

\n )}\n
\n  );\n}\nexport default MessageBox;'}

Output: Inbox and You have 5 unread messages.

Explanation: The message appears only when messageCount is greater than zero.


3. Practical Uses of Logical AND Rendering

3.1 Conditional Login Message

{'function LoginStatus() {\n  const isLoggedIn = true;\n  return (\n    
\n {isLoggedIn &&

You are successfully logged in.

}\n
\n  );\n}\nexport default LoginStatus;'}

3.2 Display Product Availability

{'function Product() {\n  const inStock = true;\n  return (\n    
\n

Wireless Headphones

\n {inStock &&

Available in stock

}\n
\n  );\n}\nexport default Product;'}

3.3 Show an Admin Panel

{'function Dashboard() {\n  const isAdmin = true;\n  return (\n    
\n

Dashboard

\n {isAdmin && }\n
\n  );\n}\nexport default Dashboard;'}

Note: Conditional rendering only controls what is displayed in the UI. Hiding an admin button is not an authorization or security mechanism. Permissions must also be enforced by the application backend.


4. Important Logical AND (&&) Pitfall

One common mistake is placing a number directly on the left side of the && operator.

Incorrect Example

{'function App() {\n  const messageCount = 0;\n  return (\n    
\n {messageCount &&

You have new messages.

}\n
\n  );\n}'}

Problem: When messageCount is 0, the expression evaluates to 0, and React renders the number 0 instead of rendering nothing.

Correct Example

{'function App() {\n  const messageCount = 0;\n  return (\n    
\n {messageCount > 0 &&

You have new messages.

}\n
\n  );\n}\nexport default App;'}

Explanation: The comparison messageCount > 0 produces a boolean. When the count is zero, the condition is false, so React renders no notification paragraph.

Common Falsy Values in JavaScript

  • false
  • 0 and -0
  • "" (empty string)
  • null
  • undefined
  • NaN

Best Practice: When checking numbers, use explicit comparisons such as count > 0. When checking optional values, make sure the condition matches the intended behavior.


5. What Is the Ternary Operator?

The ternary operator is a short JavaScript conditional expression used to choose between two values or JSX elements. It is called a ternary operator because it takes three parts: a condition, a result for true, and a result for false.

Syntax

{'condition ? expressionIfTrue : expressionIfFalse'}
  • Condition: The expression being checked.
  • Question mark (?): Separates the condition from the true result.
  • Colon (:): Separates the true result from the false result.

Example 1: Login and Logout

{'function App() {\n  const isLoggedIn = true;\n  return (\n    
\n {isLoggedIn ?

Welcome Back!

:

Please Log In

}\n
\n  );\n}\nexport default App;'}

Output: Welcome Back!

Explanation: When isLoggedIn is true, React displays Welcome Back! Otherwise, it displays Please Log In.

Example 2: Pass or Fail Result

{'function Result() {\n  const marks = 75;\n  return (\n    
\n

Exam Result

\n

{marks >= 40 ? "Pass" : "Fail"}

\n
\n  );\n}\nexport default Result;'}

Output: Exam Result — Pass.

Explanation: The student passes because the marks are greater than or equal to 40.

Example 3: Product Availability

{'function Product() {\n  const inStock = false;\n  return (\n    
\n

Smartphone

\n

{inStock ? "Available" : "Out of Stock"}

\n
\n  );\n}\nexport default Product;'}

Output: Smartphone — Out of Stock.


6. Ternary Rendering with JSX Elements

The ternary operator can return complete JSX elements, making it useful when two different UI sections are needed.

Example: Display Different Components

{'function AdminPanel() {\n  return 

Admin Dashboard

;\n}\nfunction UserPanel() {\n  return 

User Dashboard

;\n}\nfunction Dashboard() {\n  const isAdmin = true;\n  return (\n    
\n {isAdmin ? : }\n
\n  );\n}\nexport default Dashboard;'}

Output: Admin Dashboard.

Explanation: The AdminPanel component is rendered when isAdmin is true. Otherwise, the UserPanel component is rendered.

Example: Conditional Button Text

{'function SubscribeButton() {\n  const isSubscribed = true;\n  return (\n    <button>\n      {isSubscribed ? "Subscribed" : "Subscribe"}\n    </button>\n  );\n}\nexport default SubscribeButton;'}

Output: A button labeled Subscribed.


7. Using Ternary Rendering with useState

The useState Hook allows a component to store state and update the UI when that state changes. A ternary expression can display different content based on the current state.

Example: Toggle Login Status

{'import { useState } from "react";\nfunction LoginToggle() {\n  const [isLoggedIn, setIsLoggedIn] = useState(false);\n  return (\n    
\n

{isLoggedIn ? "Welcome Back!" : "Please Log In"}

\n \n
\n  );\n}\nexport default LoginToggle;'}

Explanation: Initially, isLoggedIn is false, so the page displays Please Log In and a Login button. Clicking the button updates the state, and React displays Welcome Back! with a Logout button. Clicking again switches the UI back.


8. Combining Logical AND and Ternary Rendering

You can use both operators in the same component when they serve different purposes. Use && to show optional content and a ternary expression to choose between two alternatives.

Example: User Dashboard

{'function UserDashboard() {\n  const isLoggedIn = true;\n  const hasPremium = true;\n  return (\n    
\n

User Dashboard

\n {isLoggedIn ?

Welcome, User!

:

Please log in.

}\n {hasPremium &&

Premium features are enabled.

}\n
\n  );\n}\nexport default UserDashboard;'}

Explanation: The ternary expression chooses between the welcome message and the login message. The && expression displays the premium message only when hasPremium is true.


9. Logical AND vs Ternary Operator

Feature Logical AND (&&) Ternary Operator (? :)
Purpose Conditionally show an element or expression. Choose between two alternative expressions.
Syntax condition && element condition ? valueA : valueB
When condition is true Evaluates and returns the right-hand expression. Returns the expression after ?.
When condition is false Returns the left-hand falsy value; booleans such as false render nothing. Returns the expression after :.
Best use Optional messages, badges, alerts, and panels. Login/logout labels, pass/fail results, and alternate components.
Example {'isAdmin &&

Admin

'}
{'isAdmin ? "Admin" : "User"'}

Quick Rule

  • Use && when you want to show something only if a condition is true.
  • Use the ternary operator when you need one output for true and another output for false.
  • Use if/else when the logic is complex or has several branches.

10. Common Mistakes

  • Using a number directly with &&: A value of 0 may appear on the screen. Use an explicit comparison such as count > 0.
  • Forgetting the false branch: A ternary expression must include both the true and false expressions.
  • Nesting too many ternary operators: Deeply nested conditions are difficult to read and maintain.
  • Confusing assignment with comparison: Use comparison operators such as === when checking equality, not =.
  • Using statements inside JSX expressions: A regular if statement cannot be inserted directly inside JSX braces as an expression. Use &&, a ternary expression, or calculate a variable before returning JSX.
  • Assuming hidden UI means secure UI: Sensitive actions and data must be protected with appropriate authorization, not just conditional rendering.

11. Best Practices

  • Use && for simple optional content.
  • Use ternary rendering for two clear alternatives.
  • Use descriptive condition names such as isLoggedIn, isLoading, and hasError.
  • Use strict comparisons such as === where appropriate.
  • Wrap multiline JSX branches in parentheses for readability.
  • Avoid complicated nested ternary expressions.
  • Move complex rendering logic into separate components or helper variables.
  • Test both true and false conditions.
  • Use explicit comparisons for numeric conditions to prevent accidental rendering of 0.

12. Practical Project: React Product Dashboard

Objective: Create a small product dashboard that displays stock status, a sale message, and a membership offer using logical AND and ternary rendering.

Complete Code

{'function ProductDashboard() {\n  const inStock = true;\n  const onSale = true;\n  const isMember = false;\n  const price = 1200;\n  return (\n    
\n

Product Dashboard

\n

Wireless Keyboard

\n

Price: ₹{price}

\n

{inStock ? "Available" : "Out of Stock"}

\n {onSale &&

Special offer available!

}\n {isMember ? (\n

Member discount applied.

\n ) : (\n

Join our membership for special offers.

\n )}\n
\n  );\n}\nexport default ProductDashboard;'}

Expected Output

  • Product Dashboard
  • Wireless Keyboard
  • Price: ₹1200
  • Available
  • Special offer available!
  • Join our membership for special offers.

Practice Tasks

  1. Change inStock to false and check the output.
  2. Change onSale to false and verify that the offer message disappears.
  3. Change isMember to true and verify that the membership discount message appears.
  4. Add a new logical AND condition that displays a message when the price is below ₹1500.
  5. Add a ternary expression that displays “Low Price” when the price is below ₹1000 and “Regular Price” otherwise.

13. Interview Questions and Answers

Q1. What is conditional rendering in React?

Answer: Conditional rendering means displaying UI elements based on conditions using JavaScript techniques such as if/else, &&, and the ternary operator.

Q2. What is the purpose of the logical AND operator in React?

Answer: The && operator is commonly used to render an element only when a condition is true or truthy.

Q3. What is the syntax of the ternary operator?

Answer: condition ? expressionIfTrue : expressionIfFalse.

Q4. What is the main difference between && and the ternary operator?

Answer: The && operator is useful for rendering optional content, whereas the ternary operator selects between two possible expressions.

Q5. What happens when the left side of && is false?

Answer: JavaScript returns the left-hand falsy value. React does not render boolean false, null, or undefined as visible text, but numeric 0 can appear.

Q6. Why should you avoid using count && element when count can be zero?

Answer: When count is zero, the expression returns 0, which React can render. Use count > 0 && element instead.

Q7. Can the ternary operator render React components?

Answer: Yes. It can select between JSX elements or components, such as and .

Q8. Can && and the ternary operator be used together?

Answer: Yes. For example, a ternary expression can choose a login message while && conditionally displays a notification.

Q9. Can you use an if statement directly inside JSX braces?

Answer: No. JSX braces accept JavaScript expressions, not statements such as if. Use &&, a ternary expression, or calculate the result before returning JSX.

Q10. When should you avoid nested ternary expressions?

Answer: Avoid them when they make the rendering logic difficult to understand. Use if/else statements, variables, or separate components for complex logic.


14. Practice Exercises

  1. Display “Welcome” only when isLoggedIn is true using &&.
  2. Display “Pass” or “Fail” using a ternary expression based on marks.
  3. Display “In Stock” or “Out of Stock” using a ternary expression.
  4. Show a discount message only when discountAvailable is true.
  5. Display an admin button only when isAdmin is true.
  6. Use useState to toggle a button label between “Enable” and “Disable”.
  7. Display a notification only when notificationCount is greater than zero.
  8. Build a profile section that shows “Edit Profile” for logged-in users and “Login” for guests.

15. Quick Revision Checklist

  • Understand conditional rendering in React.
  • Know how the logical AND (&&) operator works.
  • Understand short-circuit evaluation.
  • Know how to use the ternary operator (? :) inside JSX.
  • Understand the difference between optional content and two-way alternatives.
  • Avoid accidentally rendering 0 with the && operator.
  • Practice using both operators with props and useState.
  • Keep conditional JSX readable and easy to maintain.

16. Useful Learning Resources

Conclusion

Logical AND (&&) and ternary rendering help React developers build dynamic user interfaces with concise JavaScript expressions. Use && when content should appear only when a condition is met, and use the ternary operator when two different results are required. For complex conditions, prefer readable if/else logic or separate components. Practice these techniques with props, state, messages, forms, dashboards, and product interfaces to strengthen your React JS skills.

Start learning: JustAcademy React JS Training Course | Register for React JS Course Demo

whatsapp