What is conditional rendering in React?

👨‍💻 Frontend Developer 🟢 Almost Certain 🎚️ Easy
#React #Rendering

Brief Answer

Conditional rendering in React is the display of different elements or components based on certain conditions. React allows you to use standard JavaScript expressions and operators to control what appears on the screen.

Main conditional rendering approaches:

  • Using if/else statements
  • Ternary operator ? :
  • Logical AND operator &&
  • Conditionally returning null
  • Conditional variable assignment

Example with ternary operator:

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

Full Answer

Conditional rendering is a powerful pattern in React that allows displaying different components or elements depending on the application state. It’s one of the fundamental concepts for creating dynamic interfaces. 🧩

Conditional Rendering Methods

1. Using if/else

The classic approach using if/else to determine what to render:

function UserStatus({ isLoggedIn }) {
  if (isLoggedIn) {
    return <div>User is logged in</div>;
  } else {
    return <div>User is not logged in</div>;
  }
}

2. Ternary Operator

A concise way to embed conditional logic directly in JSX:

function Button({ isActive }) {
  return (
    <button className={isActive ? 'active' : 'inactive'}>
      {isActive ? 'Active Button' : 'Inactive Button'}
    </button>
  );
}

3. Logical AND Operator

A convenient way for conditional rendering of a single element:

function Notification({ hasMessages }) {
  return (
    <div>
      {hasMessages && <span>You have unread messages</span>}
    </div>
  );
}

4. Conditional null Return

To completely hide a component, you can return null:

function AdminPanel({ isAdmin }) {
  if (!isAdmin) {
    return null;
  }
  
  return <div>Admin Panel</div>;
}

5. Assigning Elements to Variables

A more flexible approach using variables:

function LoginControl({ isLoggedIn }) {
  let button;
  
  if (isLoggedIn) {
    button = <LogoutButton />;
  } else {
    button = <LoginButton />;
  }
  
  return (
    <div>
      <div>Status: {isLoggedIn ? 'Online' : 'Offline'}</div>
      {button}
    </div>
  );
}

Approach Comparison

MethodAdvantagesDisadvantages
if/elseSimple and clearVerbose for simple conditions
Ternary operatorCompact, integrates with JSXCan become hard to read when nested
&& operatorVery concise for simple conditionsOnly works for a single variant
Returning nullCompletely hides componentDoesn’t show an alternative
VariablesFlexible and readableRequires additional code

Common Mistakes

1. Incorrect Use of the Logical AND Operator

// ❌ Problematic code
function Counter({ count }) {
  return (
    <div>
      {count && <h1>Count: {count}</h1>}
    </div>
  );
}
// If count = 0, it will display "0" instead of the heading!

Solution:

// ✅ Correct
function Counter({ count }) {
  return (
    <div>
      {count > 0 && <h1>Count: {count}</h1>}
    </div>
  );
}

2. Complex Conditions in JSX

// ❌ Hard to read
function Component({ isAuth, isAdmin, hasPermission }) {
  return (
    <div>
      {isAuth && isAdmin ? 
        hasPermission ? <AdminPanel /> : <NoPermission /> 
        : <LoginForm />}
    </div>
  );
}

Solution:

// ✅ Better to use a variable
function Component({ isAuth, isAdmin, hasPermission }) {
  let content;
  
  if (!isAuth) {
    content = <LoginForm />;
  } else if (isAdmin && hasPermission) {
    content = <AdminPanel />;
  } else {
    content = <NoPermission />;
  }
  
  return <div>{content}</div>;
}

Optimizing Conditional Rendering

1. Use Early Returns

For complex components, early returns can improve readability:

function ProfilePage({ user, isLoading, error }) {
  if (isLoading) return <Spinner />;
  if (error) return <ErrorMessage message={error} />;
  if (!user) return <NotFound />;
  
  return <UserProfile user={user} />;
}

2. Avoid Unnecessary Rendering

Conditional rendering can lead to unnecessary re-renders:

// ❌ Component always re-renders
function Dashboard({ user }) {
  const [activeTab, setActiveTab] = useState('overview');
  
  return (
    <div>
      <Tabs activeTab={activeTab} onChange={setActiveTab} />
      {activeTab === 'overview' && <Overview user={user} />}
      {activeTab === 'settings' && <Settings user={user} />}
      {activeTab === 'profile' && <Profile user={user} />}
    </div>
  );
}

Solution:

// ✅ Object to store components
function Dashboard({ user }) {
  const [activeTab, setActiveTab] = useState('overview');
  
  const tabs = {
    overview: <Overview user={user} />,
    settings: <Settings user={user} />,
    profile: <Profile user={user} />
  };
  
  return (
    <div>
      <Tabs activeTab={activeTab} onChange={setActiveTab} />
      {tabs[activeTab]}
    </div>
  );
}

Summary

Conditional Rendering in React:

  • Allows displaying different components based on conditions
  • Uses standard JavaScript expressions
  • Can be implemented using several methods: if/else, ternary operators, &&, returning null

Recommendations:

  • Use ternary operators for simple conditions
  • Use variables or early returns for complex conditions
  • Avoid deeply nested conditions in JSX
  • Be careful with the logical AND operator when working with numbers

Proper use of conditional rendering helps create dynamic and adaptive user interfaces that respond to user actions and data changes. 🚀


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site, and improve yourself every day 💪