CPCODELAB
React

Conditional Rendering

7 min read

Showing and Hiding Elements

React lets you conditionally include or exclude JSX using plain JavaScript. The three most common patterns are the ternary operator, the logical AND short-circuit, and early returns.

jsx
function StatusBanner({ status }) {
  if (status === "loading") {
    return <p>Loading...</p>;
  }

  return (
    <div>
      {status === "error" && <p className="error">Something went wrong.</p>}
      {status === "success" ? (
        <p className="success">Data loaded!</p>
      ) : (
        <p className="idle">Waiting...</p>
      )}
    </div>
  );
}

Avoid using 0 && <Component /> — when the left side is the number 0, React renders it as the string "0" in the DOM. Use count > 0 && <Component /> instead.

Ready to test yourself?
Practice React— quiz & coding exercises