How to conditionally render elements in React

· Category: React

Short answer

React supports conditional rendering via ternary operators, logical AND (&&), if-statements outside JSX, and early returns in components.

Steps

  1. Use early returns for loading or error states before the main JSX.
  2. Use ternary operators for choosing between two elements inside JSX.
  3. Use && for rendering something only when a condition is true.
  4. Extract complex conditions into a variable or helper function for readability.

Example

function Banner({ isLoggedIn, user }) {
  if (!user) return <p>Loading...</p>;

  return (
    <div>
      {isLoggedIn ? (
        <h1>Welcome back, {user.name}</h1>
      ) : (
        <h1>Please sign in</h1>
      )}
      {user.isAdmin && <AdminPanel />}
    </div>
  );
}

Common issues

  • Beware of falsy values like 0 with &&; count && <List /> will render 0 if count is zero. Use count > 0 && <List /> instead.