Home About Skills Products
Work
Projects Services Experience
Learn
Tutorials Courses Blogs Resources
Contact
Tutorials · React JS

Ways to Do Conditional Rendering

Ways to Do Conditional Rendering

Very often, part of your UI depends on some condition — whether a user is logged in, whether something is loading. React has no special syntax for this — plain JavaScript does the job.

Ternary Operator (when there are 2 options)

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

The && Operator (when you only show something for one condition)

function Inbox({ unreadCount }) {
  return (
    <div>
      <h2>Inbox</h2>
      {unreadCount > 0 && <span className="badge">{unreadCount} new</span>}
    </div>
  );
}

⚠️ A common bug: if unreadCount is 0, the left side of && evaluates to 0 (falsy) and React literally prints "0" on screen. Fix: make the condition an actual boolean — unreadCount > 0 && ... (as shown above) or Boolean(unreadCount) && ....

if/else Statement (when logic gets complex)

function Status({ state }) {
  if (state === 'loading') {
    return <Spinner />;
  }

  if (state === 'error') {
    return <ErrorMessage />;
  }

  return <Content />;
}

When you have more than 2-3 conditions, or things start looking messy inside JSX, the early-return pattern (separate if statements, each returning its own JSX) tends to stay the most readable.

Key Takeaways

  • Use a ternary (? :) for 2 options, && for a single-option case.
  • Be careful with number conditions and && (watch out for the "0" bug).
  • Early return statements are the cleanest approach for complex logic.
What is React? JSX Introduction and Your First Component

What is React? JSX Introduction and Your First Component

What problem React actually solves, how JSX syntax works, and how to build your first component.

Setting Up a React App with Vite

Setting Up a React App with Vite

Set up a modern React project in seconds with Vite, and understand the resulting folder structure.

Understanding Components and Props

Understanding Components and Props

Build functional components and pass data from parent to child components using props.

Advertisement
Esc