Rendering DataCore· 35 min read

Conditional Rendering

Show different UI depending on the data — logged in vs out, loading vs loaded, empty vs full.

What you will learn

  • Render conditionally with the ternary operator
  • Use && for show/hide
  • Handle empty states

The ternary in JSX

Inside { }, use the ternary condition ? a : b to choose between two pieces of UI.

Ternary chooses what to render
function App() {
  const isLoggedIn = true;
  return (
    <div>
      {isLoggedIn
        ? <h3>Welcome back! 👋</h3>
        : <h3>Please log in.</h3>}
    </div>
  );
}
Live preview

The ternary reads as a question: isLoggedIn ? A : B means “if isLoggedIn is true, show A, otherwise show B”. Here isLoggedIn is true, so React shows the “Welcome back” heading. Flip it to false and the “Please log in” heading appears instead. It is a one-line if/else you can use right inside { }.

Note: Output: Welcome back! 👋 (If isLoggedIn were false, it would instead read Please log in.)

Show/hide with &&

Use condition && <Element/> to show something only when the condition is true.

&& shows UI only when true
function App() {
  const cart = ["Book", "Pen"];
  return (
    <div>
      <p>You have {cart.length} items.</p>
      {cart.length === 0 && <p>Your cart is empty.</p>}
      {cart.length > 0 && <p>Ready to checkout! ✅</p>}
    </div>
  );
}
Live preview

When you only want to show something or nothing (not an either/or), use &&. condition && <Element/> means “if the condition is true, show the element; if false, show nothing”. The cart here has 2 items, so cart.length === 0 is false (the empty message is hidden) and cart.length > 0 is true (the checkout message appears).

Note: Output: You have 2 items. Ready to checkout! ✅ The “Your cart is empty” line is skipped because the cart is not empty.

Tip: Common real use: show a “Loading…” message while data is being fetched, then the data once it arrives. You will do exactly this in the data-fetching lesson.

Q. Which is used in JSX to render one of two elements based on a condition?

Answer: JSX expressions use the ternary operator (cond ? a : b) for inline conditional rendering. Plain if statements go outside the returned JSX.

✍️ Practice

  1. Show “Adult” or “Minor” based on an age variable using a ternary.
  2. Show a “No items” message only when a list is empty using &&.

🏠 Homework

  1. Build a component that shows a login/logout button depending on an isLoggedIn value.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →