C
React/Components/Lesson 05

Conditional Rendering

20 min·theory
This chapter
3/4
JavaScript

Conditional Rendering

💡 Why Should You Learn This?

🎯 You can display different screens based on the user's state.
💼 It is frequently used in practice for login/logout flows, error messages, and more.
It is an essential technique for building dynamic and responsive websites.
🏢 실무에서는
In practice, if a user is logged in you show their profile; if they are logged out you show a login button. You also conditionally render a loading spinner while data is being fetched and an error message when an error occurs.

Conditional Rendering — Dynamic UI with && and the Ternary Operator

The && Operator Pattern

jsx
{isLoggedIn && <UserProfile />}
// Renders only when isLoggedIn is true
// Renders nothing when false

The Ternary Operator Pattern

jsx
{isLoggedIn ? <UserProfile /> : <LoginButton />}
// UserProfile if true, LoginButton if false

Watch Out: The && Pitfall

jsx
{count && <p>Count: {count}</p>}
// What if count is 0? → "0" gets rendered on screen! (bug)
// Fix: {count > 0 && <p>...</p>}

When to Use What?

SituationUse
Show or hide a single element&&
Show either A or BTernary operator
Complex conditionsif/else + variable
💻 Logged In / Logged Out + Loading Spinner + Error Message
import { useState } from 'react';

// ===== Conditional Rendering based on Login Status =====
function AuthSection() {
  // Input: Login status
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // Processing: Select different UI based on condition

  // Loading → Display spinner
  if (loading) {
    return <div className="spinner">Loading...</div>;
  }

  // Error → Display error message
  if (error) {
    return <p style={{ color: "red" }}>Error: {error.message}</p>;
  }

  // Output: Render different UI based on condition
  return (
    <div>
      {/* Ternary operator: Different components depending on login status */}
      {isLoggedIn ? (
        <div>
          <p>Welcome! 🎉</p>
          <button onClick={() => setIsLoggedIn(false)}>Logout</button>
        </div>
      ) : (
        <div>
          <p>Login required.</p>
          <button onClick={() => setIsLoggedIn(true)}>Login</button>
        </div>
      )}

      {/* && operator: Display notification only when logged in */}
      {isLoggedIn && <p>You have 3 new notifications.</p>}
    </div>
  );
}

💡 💡 Conditional Rendering Tips

  • && caution: {0 && <Comp/>} renders 0 → use {count > 0 && ...} instead
  • Early return: Handling loading/error states first keeps your code clean
  • Record map: Object mapping is cleaner than switch statements
  • null return: Return null to render nothing

This concept is fundamental to React component development. Understand React's declarative UI paradigm and clearly distinguish between props and state. A component should behave like a pure function — given the same input (props), it always returns the same output (JSX).

⚛️ React Patterns — Conditional Rendering

Learn step by step how to use conditional rendering in React, with code examples.
1 🧩 1. Scenarios for Using Conditional Rendering
Situations where this feature is needed.
2 💻 2. Writing the Code
Basic usage of conditional rendering.
3 🎨 3. Rendering Result
What the user sees on screen.
4 💡 4. Practical Tips
Common pitfalls and best practices.

🚦 Conditional Rendering

Edit the code directly and changes are reflected automatically after 0.7 seconds. Runs instantly in the browser with React 18 + Babel.
🖥️ Result — rendered React component
✏️ React 코드 수정하기 (클릭해서 열기)
⚛️ React 18 + Babel Standalone — see the result first, then edit the code yourself.

Check Your Understanding

In `{isLoggedIn && <UserProfile />}`, what happens when isLoggedIn = false?
💡 With the && operator, if the left side is false, the right side is not evaluated. React does not render false, null, or undefined. However, be careful — the number 0 is rendered as '0'!
Read this first: Props
Up next: Lists and key
Conditional Rendering - React