SmartCodingTips

🔀 Conditional Rendering in React

Conditional rendering lets you display content based on certain conditions. React provides multiple ways to control what gets rendered based on logic or user interaction.


1️⃣ Using if-else Statements

You can conditionally render different elements using plain JavaScript:

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

2️⃣ Using Ternary Operator

function Greeting({ isLoggedIn }) {
  return (
    <h2>
      {isLoggedIn ? "Welcome back!" : "Please log in."}
    </h2>
  );
}

3️⃣ Using Logical AND (&&)

function Warning({ show }) {
  return (
    <div>
      {show && <p>⚠️ This is a warning!</p>}
    </div>
  );
}

4️⃣ Separating JSX Logic

function Message({ status }) {
  let content;
  if (status === "loading") {
    content = <p>Loading...</p>;
  } else if (status === "error") {
    content = <p>❌ Something went wrong.</p>;
  } else {
    content = <p>✅ Success!</p>;
  }

  return <div>{content}</div>;
}

✅ Best Practices

  • Use && for simple checks (e.g., toggle content visibility).
  • Use ternary for small inline conditional UI.
  • Use if or extracted functions for complex logic.