Conditional Rendering in React

Conditional rendering means showing or hiding parts of the user interface based on certain conditions. Just like an if statement in JavaScript decides which code to run, React uses conditions to decide what to display on screen.

For example, a login button should only be shown when the user is not logged in. Once they log in, a logout button should appear instead. This kind of logic is handled through conditional rendering.

Using if/else Statements

The simplest way to conditionally render content is with a standard JavaScript if/else statement inside the component function:


function UserStatus({ isLoggedIn }) {
  if (isLoggedIn) {
    return <p>Welcome back! You are logged in.</p>;
  } else {
    return <p>Please log in to continue.</p>;
  }
}

function App() {
  return (
    <div>
      <UserStatus isLoggedIn={true} />
      <UserStatus isLoggedIn={false} />
    </div>
  );
}

The component checks the isLoggedIn prop and returns a different message based on its value.

The Ternary Operator

For shorter conditions that fit within JSX, the ternary operator is the most common approach. It works like a compact if/else written inline:


function DoorSign({ isOpen }) {
  return (
    <p>The door is {isOpen ? "Open" : "Closed"}.</p>
  );
}

The syntax is: condition ? valueIfTrue : valueIfFalse. If isOpen is true, it shows "Open". If false, it shows "Closed".

Rendering Entire Blocks Conditionally

The ternary operator can also render entire JSX blocks, not just text values:


import { useState } from 'react';

function Notification() {
  const [hasMessage, setHasMessage] = useState(true);

  return (
    <div>
      {hasMessage ? (
        <div>
          <strong>New Message:</strong>
          <p>You have a new notification!</p>
          <button onClick={() => setHasMessage(false)}>Dismiss</button>
        </div>
      ) : (
        <p>No new notifications.</p>
      )}
    </div>
  );
}

When the "Dismiss" button is clicked, hasMessage becomes false, and the notification block is replaced with "No new notifications."

Short-Circuit Evaluation with &&

When something should be shown only when a condition is true — and nothing should be shown when it is false — the && (AND) operator provides a clean shortcut:


function AlertMessage({ showAlert }) {
  return (
    <div>
      <h3>Dashboard</h3>
      {showAlert && <p>⚠️ System update required!</p>}
    </div>
  );
}

If showAlert is true, the paragraph is rendered. If it is false, nothing is rendered — no empty space, no placeholder. This is the most concise form of conditional rendering in React.

Important Warning with &&

When using &&, be careful with the condition being a number. If the condition is 0, React will actually render the number 0 on screen instead of rendering nothing:


// ❌ Bug — renders "0" on screen when count is 0
{count && <p>You have {count} messages.</p>}

// ✅ Fixed — converts condition to boolean first
{count > 0 && <p>You have {count} messages.</p>}

Always use a proper boolean condition to avoid this common mistake.

Conditional Rendering with State

Conditional rendering is most powerful when combined with state. This allows components to change what they display based on user interaction:


import { useState } from 'react';

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

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

      {isVisible && (
        <div>
          <h4>Details Section</h4>
          <p>Here is some extra content that appears when toggled.</p>
        </div>
      )}
    </div>
  );
}

This accordion-style pattern is very common in real applications — showing and hiding panels, dropdowns, modals, and other content sections.

Rendering Different Components Conditionally

Conditional rendering is not limited to text or HTML — entire components can be swapped based on conditions:


function AdminPanel() {
  return <div><h3>Admin Panel</h3><p>Welcome, Administrator.</p></div>;
}

function UserPanel() {
  return <div><h3>User Panel</h3><p>Welcome, User.</p></div>;
}

function Dashboard({ role }) {
  return (
    <div>
      {role === "admin" ? <AdminPanel /> : <UserPanel />}
    </div>
  );
}

If the role is "admin", the admin panel is shown. Otherwise, the user panel is shown. This pattern is commonly used for role-based interfaces.

Returning null to Render Nothing

A component can return null to render nothing at all. This is useful when a component should not appear under certain conditions:


function ErrorMessage({ error }) {
  if (!error) return null;

  return <p style={{ color: "red" }}>Error: {error}</p>;
}

If the error prop is empty or falsy, the component returns null and nothing is rendered. If there is an error message, the red paragraph appears.

Key Points

  • Conditional rendering controls which elements or components appear based on logic or state.
  • Standard if/else statements can be used inside the component function before the return.
  • The ternary operator (condition ? a : b) is ideal for inline conditions inside JSX.
  • The && operator renders content only when the condition is true — nothing is shown when false.
  • Avoid using 0 as a condition with && — use a boolean expression instead.
  • A component can return null to render nothing.

The next topic covers Lists and Keys — how to efficiently render collections of data in React.

Leave a Comment

Your email address will not be published. Required fields are marked *