What is Conditional Rendering in React?

Conditional rendering in React is the process of displaying different user interface (UI) components or elements depending on specific conditions, such as user login status, API loading states, or user interactions. This article explains how conditional rendering works and demonstrates the most common, practical methods to implement it in your React applications, including ternary operators, logical AND operators, and standard if/else statements.

In React, conditional rendering works the same way conditions work in JavaScript. You use JavaScript operators to create elements representing the current state, and React updates the UI to match them.

Here are the most common and effective ways to implement conditional rendering in React.

1. The Ternary Operator (condition ? true : false)

The ternary operator is one of the most popular methods for conditional rendering in React because it allows you to write inline conditions directly inside your JSX.

function WelcomeMessage({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
    </div>
  );
}

In this example, if isLoggedIn is true, React renders the welcome message; otherwise, it renders the sign-in prompt.

2. The Logical AND Operator (condition && expression)

When you want to render an element only if a condition is true, and render nothing if it is false, the logical && operator is the cleanest option.

function NotificationCount({ messages }) {
  return (
    <div>
      <h2>Inbox</h2>
      {messages.length > 0 && (
        <p>You have {messages.length} unread messages.</p>
      )}
    </div>
  );
}

If the condition before && evaluates to true, the element right after && will appear in the output. If it is false, React will ignore and skip it.

3. Standard if/else Statements

Standard if/else statements cannot be used directly inside JSX brackets {}. Instead, they must be used outside of the return statement, typically at the beginning of your component.

function UserGreeting({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h1>Welcome back!</h1>;
  }
  return <h1>Please sign in.</h1>;
}

This approach is highly readable and works best for larger components where the layout changes drastically based on the condition.

4. Preventing Rendering with null

Sometimes you want a component to hide itself entirely based on a condition. To prevent a component from rendering, you can return null from its render output.

function WarningBanner({ warn }) {
  if (!warn) {
    return null;
  }

  return (
    <div className="warning">
      Warning! An error has occurred.
    </div>
  );
}

In this case, if the warn prop is false, the component returns null and does not render anything to the DOM.