Skip to content
beginnerPhase 36 · React

Conditional Rendering

Render different UI based on conditions with &&, ternary, and early returns.

30m
0 problems
Topic Progress0%

if/else

if/else

Use if/else statements outside JSX for complex conditions.

Basic if/else

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

Multiple Conditions

function Status({ statusCode }) {
  if (statusCode >= 200 && statusCode < 300) {
    return <span className="success">Success</span>;
  } else if (statusCode >= 400 && statusCode < 500) {
    return <span className="error">Client Error</span>;
  } else if (statusCode >= 500) {
    return <span className="error">Server Error</span>;
  }
  return <span>Unknown</span>;
}

Early Returns

function UserProfile({ user }) {
  if (!user) {
    return null; // or return <Loading />;
  }

  if (!user.isActive) {
    return <div>User is inactive</div>;
  }

  // Only render if user exists and is active
  return (
    <div>
      <h2>{user.name}</h2>
      <p>{user.email}</p>
    </div>
  );
}

Helper Functions

function StatusBadge({ status }) {
  const getStatusBadge = () => {
    switch (status) {
      case "active":
        return <span className="badge green">Active</span>;
      case "inactive":
        return <span className="badge red">Inactive</span>;
      case "pending":
        return <span className="badge yellow">Pending</span>;
      default:
        return <span className="badge gray">Unknown</span>;
    }
  };

  return getStatusBadge();
}

Ternary Operator

Ternary Operator

Use ternary operators inside JSX for simple conditions.

Basic Ternary

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

Inline Styling

function TodoItem({ todo }) {
  return (
    <li style={{ textDecoration: todo.done ? "line-through" : "none" }}>
      {todo.text}
    </li>
  );
}

Nested Ternary (Avoid)

// Bad: Hard to read
{isLoggedIn ? (isAdmin ? <AdminPanel /> : <UserPanel />) : <Login />}

// Better: Use if/else or helper function
function getPanel() {
  if (!isLoggedIn) return <Login />;
  if (isAdmin) return <AdminPanel />;
  return <UserPanel />;
}

return getPanel();

Ternary with Expressions

function Counter({ count }) {
  return (
    <div>
      <p>{count > 0 ? `Count: ${count}` : "No items"}</p>
    </div>
  );
}

&& Operator

&& Operator

Use && for rendering something or nothing.

Basic &&

function Mailbox({ unreadMessages }) {
  return (
    <div>
      <h1>Messages</h1>
      {unreadMessages.length > 0 && (
        <h2>You have {unreadMessages.length} unread messages.</h2>
      )}
    </div>
  );
}

Warning: Falsy Values

// Bad: Will render 0!
{count && <p>Count: {count}</p>}
// If count is 0, renders "0"!

// Good: Use explicit condition
{count > 0 && <p>Count: {count}</p>}

// Alternative
{count !== 0 && <p>Count: {count}</p>}

Multiple Conditions

function Notification({ user, notifications }) {
  return (
    <div>
      {user && notifications.length > 0 && (
        <ul>
          {notifications.map((n) => (
            <li key={n.id}>{n.message}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

&& with Expressions

function TodoList({ todos }) {
  return (
    <div>
      <h1>Todos</h1>
      {todos.length === 0 && <p>No todos yet!</p>}
      {todos.length > 0 && (
        <ul>
          {todos.map((todo) => (
            <li key={todo.id}>{todo.text}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

Early Returns

Early Returns

Use early returns to handle edge cases before main render.

Basic Early Return

function UserProfile({ user }) {
  if (!user) {
    return <Loading />;
  }

  return (
    <div>
      <h2>{user.name}</h2>
      <p>{user.email}</p>
    </div>
  );
}

Multiple Early Returns

function DataTable({ data, isLoading, error }) {
  if (error) {
    return <ErrorMessage message={error} />;
  }

  if (isLoading) {
    return <LoadingSpinner />;
  }

  if (!data || data.length === 0) {
    return <EmptyState />;
  }

  return (
    <table>
      {/* Render data */}
    </table>
  );
}

Early Return with Guard Clauses

function AuthenticatedRoute({ isAuthenticated, children }) {
  if (!isAuthenticated) {
    return <Navigate to="/login" />;
  }

  return children;
}

// Usage
<AuthenticatedRoute isAuthenticated={user !== null}>
  <Dashboard />
</AuthenticatedRoute>

Benefits of Early Returns

  • Reduces nesting
  • Makes code easier to read
  • Handles edge cases explicitly
  • Follows "fail fast" principle

Practice Problems

0/3solved
Build Conditional Rendering Component

Create a reusable React component implementing Conditional Rendering. Include proper state management and accessibility.

Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where needed
Conditional Rendering Testing

Write unit and integration tests for Conditional Rendering using React Testing Library.

Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility tests
Conditional Rendering Performance

Optimize Conditional Rendering for performance. Consider memoization, code splitting, and bundle size.

Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysis

Quiz

1. When should you use if/else instead of ternary?

Question 1 options

2. What happens with `{count && <p>Count</p>}` when count is 0?

Question 2 options

3. What is an early return?

Question 3 options

4. When should you use the && operator?

Question 4 options

Flashcards

Question

When should you use if/else?

Answer

For complex conditions or multiple statements

Question

What is the problem with {count && ...} when count is 0?

Answer

It renders 0 because 0 is falsy but is still a valid value

Question

What is an early return?

Answer

Returning before the main render logic to handle edge cases

Question

When should you use ternary?

Answer

For simple inline conditions that return different JSX

Question

What is Conditional Rendering?

Answer

Conditional Rendering is a key concept in frontend development.

Revision Notes

Key Takeaways

  • 1.if/else is best for complex conditions
  • 2.Ternary is good for simple inline conditions
  • 3.&& renders something or nothing
  • 4.Avoid {count && ...} when count can be 0
  • 5.Early returns reduce nesting and improve readability

Interview Tips

  • Show different conditional rendering techniques
  • Explain the gotcha with falsy values and &&
  • Demonstrate early returns for cleaner code

Cheat Sheet

Cheat Sheet

if/else

if (condition) {
  return <A />;
} else {
  return <B />;
}

Ternary

{condition ? <A /> : <B />}

&& Operator

{condition && <A />}
{count > 0 && <p>Count: {count}</p>}

Early Return

if (!user) return <Loading />;
return <UserProfile user={user} />;