Conditional Rendering in React

Sometimes, you want to show or hide parts of your UI depending on:

  • A state value
  • Props
  • A condition (like count > 0, isLoggedIn, etc.)

React lets you do that easily using JavaScript logic inside JSX.

✅ 6.1 Option 1: if statements (outside JSX)

Use if before the return to decide what to render.

function Greeting(props) {
  if (!props.name) {
    return <p>Hello, Guest!</p>;
  }

  return <p>Hello, {props.name}!</p>;
}

✅ 6.2 Option 2: && for short conditions

{count > 0 && <p>You clicked {count} times</p>}

If count > 0 is true, it renders the <p>.

If false, renders nothing.

✅ 6.3 Option 3: Ternary Operator (? :)

<p>{isLoggedIn ? "Welcome back!" : "Please log in."}</p>

If isLoggedIn is true → shows “Welcome back!”

Else → “Please log in.”

✅ 6.4 Example with useState

import { useState } from "react";

function LoginControl() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  return (
    <div>
      <h2>{isLoggedIn ? "Welcome!" : "Please Log In"}</h2>
      <button onClick={() => setIsLoggedIn(!isLoggedIn)}>
        {isLoggedIn ? "Logout" : "Login"}
      </button>
    </div>
  );
}

🧠 What’s happening?

  • isLoggedIn is a boolean state.
  • The text and button label change based on the condition.
  • You toggle state with setIsLoggedIn(!isLoggedIn).

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *