React Mastery / React Basics

Conditional Rendering

⚡ What is Conditional Rendering in React?

Conditional rendering in React means showing different UI elements based on a condition (like login status, loading state, permissions, etc.).

Just like JavaScript, React uses if, ternary operators, logical operators, and functions to decide what to render.


🧠 Why is it useful?

  • To show different UI based on user actions

  • To display loading indicators, error messages, or success states

  • To hide or show components based on user login, roles, etc.


✅ Common Ways to Do Conditional Rendering

1. Using if / else (Before return)

Best when logic is complex.

const isLoggedIn = true;

export default function App() {
  if (isLoggedIn) {
    return <h2>Welcome back!</h2>;
  } else {
    return <h2>Please log in</h2>;
  }

  return <h1>Hello world</h1>; // Skips this
}

🔹 Output

  • isLoggedIn = true → Welcome back!

  • isLoggedIn = false → Please log in


2. Using Ternary Operator (? :)

Most commonly used for simple conditions.

const isLoggedIn = true;

export default function App() {
  return (
    <button>
      {isLoggedIn ? "Logout" : "Login"}
    </button>
  )
}

🔹 Output

  • true → Logout

  • false → Login


3. Using Logical AND (&&)

Used when you want to render something or nothing.

const count = 3;

export default function App() {
  return <div>{count > 0 && <p>You have {count} notifications</p>}</div>;
}

🔹 Output

  • count = 3 → You have 3 notifications

  • count = 0 → (renders nothing)

📌 If the condition is false, React ignores it.


4. Using Logical OR (||)

Useful for fallback values.

const name = "";

export default function App() {
  return <h3>{name || "Guest User"}</h3>;
}

🔹 Output

  • name = "Codeveda" → Codeveda

  • name = "" or null → Guest User


5. Conditional Rendering with Functions

Good for clean and reusable logic.

const status = "loading";

export default function App() {
  const renderStatus = () => {
    if (status === "loading") return <p>Loading...</p>;
    if (status === "success") return <p>Data Loaded</p>;
    if (status === "error") return <p>Error occurred</p>;
  };

  return <div>{renderStatus()}</div>;
}

🔹 Output

  • "loading" → Loading...

  • "success" → Data Loaded

  • "error" → Error occurred


✅ 6. Conditional Rendering with Components

Render different components based on condition.

import AdminPanel from './AdminPanel';
import UserPanel form './UserPanel';

const isAdmin = true;

export default function App() {
  <div>
      { isAdmin ? <AdminPanel /> : <UserPanel /> }
</div>
}

❌ Common Mistake

❌ Using if inside JSX directly

// ❌ This will cause error
<div>
    if (isLoggedIn) {
      <p>Welcome</p>
    }
</div>

✔️ Use ternary or && instead.


🧠 When to Use What?

Scenario

Best Choice

Complex logic

if / else

Simple toggle

Ternary (? :)

Show or hide

&&

Default value

||

Multiple states

Function