Menu

Conditional Rendering in React: Ternary, && & More

Conditional Rendering

What is Conditional Rendering?

Showing different UI depending on a condition, a login form when logged out, a dashboard when logged in.

Why is it Used?

Almost every real interface has conditional parts: loading spinners, empty states, error messages, admin-only buttons.

The Three Approaches

1. Ternary operator: when there are two outcomes

jsx

{isLoggedIn ? <Dashboard /> : <LoginForm />}

2. Logical AND: when there is one outcome or nothing

jsx

{hasError && <p className="error">Something went wrong</p>}

If hasError is false, nothing renders.

3. Early return: when the whole component differs

jsx

function CourseList({ courses }) {
  if (courses.length === 0) {
    return <p>You have not enrolled in any courses yet.</p>;
  }

  return <ul>{/* ...course items... */}</ul>;
}

Example

src/components/CourseStatus.jsx

jsx

function CourseStatus({ isEnrolled, progress, certificateReady }) {
  if (!isEnrolled) {
    return <button>Enrol now</button>;
  }

  return (
    <div>
      <p>Progress: {progress}%</p>

      {progress === 100 ? (
        <p className="success">Course completed</p>
      ) : (
        <button>Continue learning</button>
      )}

      {certificateReady && <button>Download certificate</button>}
    </div>
  );
}

export default CourseStatus;

How It Works

  • The early return handles the "not enrolled" case first, keeping the main JSX clean.
  • The ternary chooses between a completion message and a continue button.
  • The && shows the certificate button only when certificateReady is true.

Common Mistakes Beginners Make

  • Using && with a number. {count && <p>Items</p>} renders the literal 0 on screen when count is 0, because 0 is falsy but still renders. Use {count > 0 && <p>Items</p>} instead.
  • Writing if inside JSX. It does not work. Use a ternary, or move the if above the return.
  • Deeply nested ternaries. More than one level becomes unreadable — use early returns or a separate component.

ReactJS Tutorial



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details