React Conditional Rendering

n this guide, we delve deep into three fundamental methods of conditional rendering in React: if statements, logical && operators, and ternary operators, each illustrated with practical examples. Whether you are new to React or looking to brush up your skills, this guide will enhance your understanding and application of these techniques.

1. If Statement

The if statement is the most straightforward way to perform conditional rendering in React. It allows you to render different components or elements based on a specific condition.

Example:

Consider a scenario where you want to display a welcome message only to logged-in users.

function WelcomeMessage({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h1>Welcome back!</h1>;
  }
  return <h1>Welcome, guest!</h1>;
}

In this example, the WelcomeMessage component checks the isLoggedIn prop. If it’s true, it renders a welcome back message; otherwise, it shows a generic welcome message for guests.

2. Logical & Operator

The logical && operator is a concise way to render components based on a condition. It’s particularly useful when you want to render something if the condition is true, and render nothing if it’s false.

Example:

Let’s say you want to display a notification badge if there are unread messages.

function NotificationBadge({ unreadMessages }) {
  return (
    <div>
      {unreadMessages.length > 0 && 
        <span>You have {unreadMessages.length} unread messages</span>}
    </div>
  );
}

In this case, if unreadMessages.length is greater than 0, the message span will be rendered. If it’s 0, nothing after the && operator gets executed, thus rendering nothing.

3. Ternary Operator

The ternary operator is a more flexible option for conditional rendering. It allows you to render one of two components based on a condition, much like an if-else statement.

Example:

Imagine a scenario where you want to display a different button based on the user’s subscription status.

function SubscriptionButton({ isSubscribed }) {
  return (
    <div>
      {isSubscribed ? 
        <button>Renew Subscription</button> : 
        <button>Subscribe Now</button>}
    </div>
  );
}

Here, the SubscriptionButton component uses the ternary operator to decide which button to render. If isSubscribed is true, it shows the “Renew Subscription” button; otherwise, it shows the “Subscribe Now” button.