Conditional rendering
Showing UI only under some condition is everyday React. Three patterns cover nearly every case.
Ternary, choose between two things:
<p>{isSaved ? "Saved ✓" : "Unsaved changes"}</p>Logical &&, show or nothing:
{error && <p className="error">{error}</p>}In Advanced JavaScript you learned && short-circuits: if the left side is falsy it returns the left side, otherwise it returns the right side. React renders false, null, and undefined as nothing, so a falsy left side hides the element.
Early return, skip the whole component:
function Banner({ show }) { if (!show) return null; return <div className="banner">Sale ends today!</div>; }
Returning null renders nothing. Full statements like if are allowed here because we are above the JSX, in plain function-body land.
The zero gotcha
React renders false as nothing, but it renders the number 0 as a visible "0". That makes one && pattern dangerous:
{unread && <p>You have mail</p>}If unread is 0, the expression evaluates to 0, and a stray 0 appears on screen. Fix it by making the left side a real boolean:
{unread > 0 && <p>You have mail</p>}Code exercise · javascript
See the zero gotcha in plain JavaScript. && returns its left side when falsy, so the first line yields 0, which React would render as a visible zero. Comparisons return real booleans, which React renders as nothing.
Quiz
Predict the render for items = []: ```jsx <div> {items.length && <p>{items.length} items</p>} </div> ```
Problem
A component should render nothing at all when the user prop is missing. Inside the component, before the JSX, you write: if (!user) return ____. What value fills the blank?