BeginnerReact Concepts

Conditional Rendering in React – Show What You Want, Hide the Rest

React lets you show or hide parts of the UI based on conditions. In this article, you’ll explore how to use if, ternary, and logical && operators for conditional rendering — just like setting rules for dynamic UI behavior.

By Rudraksh Laddha

Last week I was debugging a dashboard in Virendana Ui where buttons kept showing up for unauthorized users. The issue? Poor conditional rendering logic that leaked sensitive UI elements.

This reminded me of childhood rules:

"Only speak when spoken to during dinner parties"

React works similarly — you control what users see based on application state, user permissions, and business logic.

This is Conditional Rendering — the foundation of dynamic user interfaces.


What is Conditional Rendering?

In React, you programmatically control UI visibility based on component state, props, user authentication, feature flags, or any JavaScript expression that evaluates to true or false.

Think of it as your UI's decision engine:

"Show the admin panel only if user.role === 'admin' AND user.permissions.includes('dashboard')"

React evaluates these conditions on every render, ensuring your UI stays synchronized with application state.


Most Common Ways to Write Conditional Rendering in React

✅ 1. Ternary Operator

The go-to pattern for simple either/or scenarios. I use this for loading states and basic toggles.

const isLoggedIn = !!user?.id;

return (
  <h1>{isLoggedIn ? "Welcome back!" : "Please login."}</h1>
);

Pro tip: Notice the !!user?.id pattern — it safely checks for user existence and converts to boolean.
Ternary operators are perfect when you need exactly two outcomes.

✅ 2. Logical && (Short-circuit rendering)

This is my preferred method for optional UI elements that should only appear under specific conditions.

{user?.subscription?.tier === 'premium' && (
  <div className="premium-badge">
    <StarIcon /> Premium Member
  </div>
)}

Critical gotcha: Be careful with numbers and arrays. {count && <Component />} fails when count is 0.
Always use explicit boolean conversion: {count > 0 && <Component />}

✅ 3. if-else Statement (More Control)

When logic gets complex, I extract it outside JSX for better readability and testing:

function getStatusMessage(status, error) {
  if (status === 'loading') return <Spinner />;
  if (status === 'error') return <ErrorAlert message={error} />;
  if (status === 'empty') return <EmptyState />;
  return <DataTable />;
}

return <div>{getStatusMessage(apiStatus, apiError)}</div>;

✅ 4. Early Return (Component Skip Logic)

Essential for performance and security. I use this pattern extensively for permission checks:

function AdminPanel({ user }) {
  // Security: Don't even render if unauthorized
  if (!user?.permissions?.includes('admin')) {
    return null;
  }
  
  // Performance: Skip expensive operations
  if (!user.isActive) {
    return <AccountSuspendedMessage />;
  }
  
  return <ComplexAdminDashboard />;
}

✅ 5. Switch Case (Multiple conditions)

function getViewByUserRole(role) {
  switch (role) {
    case 'admin':
      return <AdminDashboard />;
    case 'moderator':
      return <ModeratorPanel />;
    case 'premium':
      return <PremiumUserDashboard />;
    case 'basic':
      return <BasicUserDashboard />;
    default:
      return <GuestView />;
  }
}

✅ 6. Function-based Conditions

This pattern has saved me countless hours when dealing with complex business logic:

function getUserDashboard(user, features) {
  // Complex business logic isolated and testable
  if (!user) return <LoginPrompt />;
  
  if (user.trialExpired && !user.subscription) {
    return <UpgradePrompt />;
  }
  
  if (features.maintenanceMode) {
    return <MaintenanceMessage />;
  }
  
  return <MainDashboard user={user} />;
}

return <div>{getUserDashboard(currentUser, featureFlags)}</div>;

Real-World Use Cases

Scenario Conditional Logic You'd Use
Authentication gates Early return with user.isAuthenticated checks
API loading states Ternary operator with loading, error, and success states
Form validation feedback Logical && with touched && errors conditions
Feature flags Environment-based conditional rendering
Responsive design Custom hooks with window.matchMedia

🚀 Bonus: Tips for Better Conditional Rendering

  • ✅ Extract complex conditions into custom hooks for reusability
  • ✅ Use TypeScript to catch conditional rendering bugs at compile time
  • ✅ Consider React.Suspense for async conditional rendering
  • ✅ Always handle the "loading" and "error" states explicitly
  • ✅ Use React.memo() to prevent unnecessary re-renders of conditional components

Questions I Get Asked About Conditional Rendering in React

1. What is conditional rendering in React?

It's the technique of dynamically showing or hiding UI elements based on JavaScript expressions that evaluate component state, props, or external conditions.

2. What's the difference between && and ternary rendering?

Logical && renders something OR nothing (one outcome). Ternary operator always renders one of two options (two outcomes). Choose based on your specific UI needs.

3. Can I use if-else inside JSX?

No, JSX doesn't support statements, only expressions. Use if-else outside JSX to determine what to render, then return the result.

4. What happens if I return null in React?

React skips rendering that component entirely — it won't appear in the DOM and won't trigger lifecycle methods. Perfect for conditional component mounting.

5. What's the best way to handle multiple UI states?

Use a state machine pattern with enums or constants. Create dedicated functions for complex logic and consider useReducer for managing multiple related states.

❤️ At Learn Virendana, we love creating high-quality React tutorials that simplify complex concepts and deliver a practical, real-world React learning experience for developers