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 – Complete Notes

Logical AND and Ternary Rendering are important conditional rendering techniques in React JS. They allow developers to display, hide, or change UI elements according to conditions, props, state, and user interactions. The logical AND operator is useful when content should appear only when a condition is true, while the ternary operator is useful when the UI must display one of two alternatives.

Course Link: JustAcademy React JS Training

Demo Link: Register for React JS Course Demo


1. Introduction to Conditional Rendering

Conditional rendering means displaying different UI elements based on whether a particular condition is satisfied. React uses standard JavaScript expressions and statements to decide which JSX elements should appear on the screen.

For example, a React application may show a notification when a user has unread messages, display a login button when the user is logged out, or show a logout button when the user is logged in.

Example

function Greeting() {
  const isLoggedIn = true;

  return (
    <div>
      {isLoggedIn ? <h2>Welcome Back!</h2> : <h2>Please Log In</h2>}
    </div>
  );
}
export default Greeting;

Explanation: The ternary operator checks isLoggedIn. If the value is true, React displays “Welcome Back!”. Otherwise, it displays “Please Log In”.

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

The logical AND operator, written as &&, is a JavaScript operator that evaluates two expressions. It is commonly used in React when a particular UI element should be displayed only if a condition is satisfied.

In JavaScript, the AND operator evaluates the left operand first. If the left operand is falsy, it returns that operand without evaluating the right operand. If the left operand is truthy, it evaluates and returns the right operand.

Syntax

{condition && expression}

In React JSX, this pattern is commonly used to render an element when a condition is true and render nothing visible for a Boolean false result.

Example: Displaying a Welcome Message

function WelcomeMessage() {
  const isLoggedIn = true;

  return (
    <div>
      <h2>User Dashboard</h2>
      {isLoggedIn && <p>Welcome to your account!</p>}
    </div>
  );
}
export default WelcomeMessage;

Explanation:

  • The isLoggedIn variable stores a Boolean value.
  • When it is true, the expression after && is evaluated and the welcome message appears.
  • When it is false, the expression evaluates to false, which React does not display as visible content.
  • The heading remains visible in both cases.

3. Why Use Logical AND Rendering in React?

  • Conditional display: Show an element only when a condition is true.
  • Less code: Avoid writing a full if/else statement for simple conditions.
  • Notifications: Display alerts when messages or updates are available.
  • Form validation: Show validation errors only when required.
  • User permissions: Display relevant interface options based on application state.
  • Task management: Display completion labels for finished tasks.
  • Optional content: Include subtitles, badges, and additional information when available.

4. Logical AND Rendering with Boolean Conditions

Boolean conditions are particularly suitable for logical AND rendering because they evaluate to either true or false.

Example: Showing an Admin Message

function AdminMessage() {
  const isAdmin = true;

  return (
    <div>
      <h2>Dashboard</h2>
      {isAdmin && <p>You have administrator access.</p>}
    </div>
  );
}
export default AdminMessage;

Explanation: The administrator message appears only when isAdmin is true. When it is false, the message is not displayed.

Example: Displaying a Warning

function WarningMessage() {
  const hasWarning = true;

  return (
    <div>
      <h2>Form Status</h2>
      {hasWarning && <p>Please review your information.</p>}
    </div>
  );
}

This pattern is useful when the warning should appear only under a particular condition.

5. Logical AND Rendering with Props

Props allow a parent component to pass information to a child component. The child can use a prop as the condition for displaying optional content.

Example

function UserBadge({ isPremium }) {
  return (
    <div>
      <h2>User Profile</h2>
      {isPremium && <span>Premium Member</span>}
    </div>
  );
}

function App() {
  return (
    <div>
      <UserBadge isPremium={true} />
      <UserBadge isPremium={false} />
    </div>
  );
}
export default App;

Explanation: The first component displays the Premium Member label because its prop is true. The second component does not display the label.

6. Logical AND Rendering with State

React state allows the UI to respond to user interactions. When a state value changes, React can render the component again and display the content appropriate to the new value.

Example: Show and Hide a Message

import { useState } from "react";

function ToggleMessage() {
  const [showMessage, setShowMessage] = useState(false);

  return (
    <div>
      <button onClick={() => setShowMessage(!showMessage)}>
        Toggle Message
      </button>
      {showMessage && <p>This message is now visible!</p>}
    </div>
  );
}
export default ToggleMessage;

How it works:

  1. The state variable showMessage starts as false.
  2. The button click updates the state to its opposite value.
  3. When the value becomes true, the message appears.
  4. When the value becomes false, the message disappears.

7. Logical AND Rendering for Notifications

Notification badges are a common practical use of the logical AND operator. A badge can be displayed only when the user has one or more unread messages.

Example

function MessageNotification() {
  const unreadMessages = 5;

  return (
    <div>
      <h2>Inbox</h2>
      {unreadMessages > 0 && (
        <p>You have {unreadMessages} unread messages.</p>
      )}
    </div>
  );
}
export default MessageNotification;

Explanation: When unreadMessages is greater than zero, the notification appears. When the count is zero, the notification is omitted.

Important: Avoid the Zero Rendering Problem

A common mistake is using a number directly on the left side of &&.

Incorrect example:

function MessageCount() {
  const unreadMessages = 0;

  return (
    <div>
      {unreadMessages && <p>You have unread messages.</p>}
    </div>
  );
}

When unreadMessages is zero, JavaScript returns zero from the expression. React can display the number 0 on the screen instead of rendering nothing.

Correct example:

function MessageCount() {
  const unreadMessages = 0;

  return (
    <div>
      {unreadMessages > 0 && (
        <p>You have unread messages.</p>
      )}
    </div>
  );
}

By using unreadMessages > 0, the left side becomes a Boolean expression, preventing the unintended display of zero.

8. What Is Ternary Rendering?

Ternary rendering uses JavaScript's conditional, or ternary, operator to choose between two expressions. It is particularly useful when React needs to display one UI element when a condition is true and another when it is false.

Syntax

condition ? expressionIfTrue : expressionIfFalse

The ternary operator contains three parts:

  1. Condition: The expression that is evaluated.
  2. Question mark (?): Separates the condition from the true expression.
  3. Colon (:): Separates the true expression from the false expression.

Example: Login and Logout

function AuthButton() {
  const isLoggedIn = true;

  return (
    <button>
      {isLoggedIn ? "Logout" : "Login"}
    </button>
  );
}
export default AuthButton;

Explanation: When isLoggedIn is true, the button displays Logout. When it is false, the button displays Login.

9. Ternary Rendering with JSX Elements

The ternary operator can select complete JSX elements, not just text. This is helpful when two conditions require different buttons, messages, or components.

Example: Login Interface

function LoginPanel() {
  const isLoggedIn = false;

  return (
    <div>
      {isLoggedIn ? (
        <div>
          <h2>Welcome Back!</h2>
          <button>Logout</button>
        </div>
      ) : (
        <div>
          <h2>Welcome Guest!</h2>
          <button>Login</button>
        </div>
      )}
    </div>
  );
}
export default LoginPanel;

Explanation: The component displays the guest interface because isLoggedIn is false. If the value changes to true, React renders the logged-in interface instead.

10. Ternary Rendering for Product Availability

E-commerce applications often use ternary rendering to display different messages based on whether a product is available.

Example

function ProductStatus() {
  const inStock = true;

  return (
    <div>
      <h2>Wireless Headphones</h2>
      <p>
        {inStock ? "Product Available" : "Out of Stock"}
      </p>
      {inStock ? (
        <button>Add to Cart</button>
      ) : (
        <button disabled>Unavailable</button>
      )}
    </div>
  );
}
export default ProductStatus;

Explanation: When the product is in stock, the availability message and Add to Cart button are displayed. Otherwise, the unavailable message and disabled button are displayed.

11. Ternary Rendering with Props

A component can receive props and use them to decide which content to render. This allows the same component to be reused in different situations.

Example

function StatusLabel({ isOnline }) {
  return (
    <span>
      {isOnline ? "Online" : "Offline"}
    </span>
  );
}

function App() {
  return (
    <div>
      <StatusLabel isOnline={true} />
      <StatusLabel isOnline={false} />
    </div>
  );
}
export default App;

Explanation: The first instance displays Online, and the second displays Offline. Both use the same reusable component.

12. Ternary Rendering with State

State can control which expression the ternary operator selects. This is commonly used for toggle buttons, expandable panels, and interactive interfaces.

Example: Show or Hide Details

import { useState } from "react";

function Details() {
  const [isVisible, setIsVisible] = useState(false);

  return (
    <div>
      <button onClick={() => setIsVisible(!isVisible)}>
        {isVisible ? "Hide Details" : "Show Details"}
      </button>

      {isVisible ? (
        <p>These are the additional details.</p>
      ) : (
        <p>Details are currently hidden.</p>
      )}
    </div>
  );
}
export default Details;

Explanation: The button label and the paragraph change when the state changes. The ternary operator chooses the correct output on each render.

13. Ternary Rendering for Form Validation

Forms often need to display a different message depending on whether the input is valid. A ternary expression can handle simple validation feedback.

Example

function EmailValidation() {
  const email = "[email protected]";
  const isValid = email.includes("@");

  return (
    <div>
      <label>Email: {email}</label>
      <p>
        {isValid ? "Email format looks valid." : "Enter a valid email."}
      </p>
    </div>
  );
}
export default EmailValidation;

Explanation: If isValid is true, the success message appears. Otherwise, the error message is shown. This is a simplified example and does not provide complete email validation.

14. Using Logical AND and Ternary Rendering Together

Both operators can be used in the same component because they solve different rendering problems. Use logical AND when an element should appear only under a condition. Use a ternary operator when you need to choose between two alternatives.

Example

function UserDashboard() {
  const isLoggedIn = true;
  const hasNotifications = true;

  return (
    <div>
      {isLoggedIn ? (
        <h2>Welcome to Your Dashboard</h2>
      ) : (
        <h2>Please Log In</h2>
      )}

      {hasNotifications && (
        <p>You have new notifications.</p>
      )}
    </div>
  );
}
export default UserDashboard;

Explanation:

  • The ternary operator selects the dashboard heading or login heading.
  • The logical AND operator displays the notification only when hasNotifications is true.
  • The two expressions work together to create a dynamic interface.

15. Difference Between Logical AND and Ternary Rendering

Logical AND (&&) Ternary (? :)
Used when content should appear only if a condition is true. Used to select between two possible expressions.
Does not require a separate false-branch expression. Requires both true and false expressions.
Syntax: condition && content Syntax: condition ? trueContent : falseContent
Useful for notifications, badges, warnings, and optional elements. Useful for login buttons, status labels, messages, and alternate components.
Can return a falsy operand such as zero, which may become visible in React. Returns whichever branch is selected by the condition.
Often shorter when the false case needs no visible content. More appropriate when both outcomes need different content.

16. Logical AND vs. Ternary: Choosing the Right Pattern

Use logical AND when you want to show something or show nothing. Use the ternary operator when you want to show one thing or another.

Logical AND Example

{hasError && <p>Please correct the error.</p>}

This displays the error message only when hasError is true.

Ternary Example

{hasError ? <p>An error occurred.</p> : <p>Everything is working.</p>}

This displays an error message when the condition is true and a success message when it is false.

17. Common Mistakes in Logical AND and Ternary Rendering

Mistake 1: Using a Number Directly with &&

Incorrect:

{items.length && <p>Items available</p>}

If items.length is zero, React may display the number zero. Instead, write:

{items.length > 0 && <p>Items available</p>}

Mistake 2: Forgetting the Colon in a Ternary Expression

Incorrect:

{isLoggedIn ? "Welcome"}

Correct:

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

A ternary expression requires a condition, a true expression, and a false expression.

Mistake 3: Using Nested Ternary Operators Excessively

Nested ternaries can become difficult to read when there are many conditions. For complex rendering logic, use if/else statements, early returns, or separate components.

Mistake 4: Using && When Both Outcomes Need Content

If the UI must display different content for both true and false conditions, a ternary operator is usually more suitable.

Mistake 5: Expecting a Normal Variable to Trigger a Re-render

Changing a regular JavaScript variable does not automatically cause React to render again. Use React state when the UI must respond to user actions.

Mistake 6: Confusing UI Visibility with Security

Hiding an administrative button or private section is not enough to protect sensitive operations. Backend authorization must enforce access permissions.

18. Best Practices

  • Use logical AND for optional UI that should appear only when a condition is true.
  • Use a ternary operator when you need to choose between two alternatives.
  • Use explicit Boolean comparisons for numeric conditions such as message counts.
  • Keep conditional expressions short and readable.
  • Avoid excessive nested ternary expressions.
  • Use meaningful condition names such as isLoggedIn, hasError, and isAvailable.
  • Use state for interactive UI that changes in response to events.
  • Test both true and false cases.
  • Handle loading, error, empty, and success states when displaying API data.
  • Enforce sensitive access rules on the server rather than relying on rendering logic.

19. Practical Project: Student Result Dashboard

This mini project combines logical AND and ternary rendering to display a student's result, pass/fail status, and an optional achievement message.

Complete Code

function StudentResult() {
  const studentName = "Rahul";
  const marks = 82;
  const resultSubmitted = true;

  return (
    <div>
      <h2>Student Result Dashboard</h2>

      {resultSubmitted ? (
        <div>
          <p>Student Name: {studentName}</p>
          <p>Marks: {marks}</p>

          <p>
            Result: {marks >= 40 ? "Pass" : "Fail"}
          </p>

          {marks >= 75 && (
            <p>Excellent performance!</p>
          )}
        </div>
      ) : (
        <p>The result has not been submitted yet.</p>
      )}
    </div>
  );
}
export default StudentResult;

Project Explanation

  1. The studentName variable stores the student's name.
  2. The marks variable stores the student's marks.
  3. The outer ternary operator checks whether the result has been submitted.
  4. The inner ternary operator determines whether the student has passed or failed.
  5. The logical AND operator displays the achievement message only when marks are 75 or higher.

Practice Extensions

  • Display “Distinction” when marks are 90 or higher.
  • Display a different message when marks are below 40.
  • Show a loading message before displaying the result.
  • Add a button that toggles the result details using useState.
  • Handle missing student information.

20. Interview Questions and Answers

Q1. What is logical AND rendering in React?

It is a conditional rendering technique that uses JavaScript's && operator to include JSX when a condition is truthy.

Q2. What is ternary rendering?

Ternary rendering uses the JavaScript conditional operator to select one of two expressions based on a condition.

Q3. What is the syntax of the ternary operator?

condition ? expressionIfTrue : expressionIfFalse.

Q4. When should you use logical AND rendering?

Use it when you want an element to appear only if a condition is true and do not need alternate content for the false case.

Q5. When should you use ternary rendering?

Use it when you need to display one of two alternatives, such as a Login or Logout button.

Q6. Why can zero appear when using &&?

JavaScript's AND operator returns an operand. When the left operand is zero, the expression evaluates to zero, which React can display.

Q7. Can logical AND and ternary rendering be used together?

Yes. A ternary can select between two main views while logical AND conditionally adds optional content.

Q8. Can these techniques work with props?

Yes. Components can use Boolean or other prop values to determine which elements to render.

Q9. Can these techniques work with state?

Yes. When state changes, React can render the component again and evaluate the conditional expressions with the new values.

Q10. What is the difference between logical AND and a ternary operator?

Logical AND is generally used for “show this or nothing,” while a ternary operator is used for “show this or that.”

21. Practice Exercises

  1. Use && to display a notification when unread messages are greater than zero.
  2. Use a ternary operator to display Online or Offline based on a Boolean prop.
  3. Create a product card that displays an Add to Cart button when a product is available.
  4. Use state to show or hide additional information.
  5. Display a success or error message using a ternary expression.
  6. Create a student result component that displays an achievement message only when marks are at least 75.
  7. Fix a component that accidentally displays zero when a count is empty.
  8. Build a dashboard that combines a ternary heading and an optional notification message.

22. Quick Revision Checklist

  • Understand the purpose of conditional rendering.
  • Know the syntax of the logical AND operator.
  • Understand how truthy and falsy values affect &&.
  • Know why zero can accidentally appear in the UI.
  • Understand the three parts of the ternary operator.
  • Know when to use logical AND and when to use a ternary.
  • Practice conditional rendering with props and state.
  • Understand how to display optional messages and alternative components.
  • Avoid deeply nested ternary expressions.
  • Test both true and false conditions.

23. Conclusion

Logical AND and Ternary Rendering are useful techniques for creating dynamic React JS interfaces. Logical AND is best for displaying optional elements when a condition is satisfied, while the ternary operator is useful for selecting between two alternatives. By practising these patterns with props, state, forms, notifications, product cards, and dashboards, developers can write concise, readable, and maintainable React code.

Learn more through JustAcademy React JS Training or register for a React JS course demo.

Official Learning Resource: React Documentation – Conditional Rendering.

Previous Next
whatsapp