Dynamic UIs & Conditional Rendering

Pascual Vila
Senior Frontend Engineer // Code Syllabus
In React, building a static website is only half the story. The true power of React is in building dynamic user interfaces that respond to state, props, and user interactions.
Pattern 1: Ternary Operator (`? :`)
This is the most common and concise way to handle a simple `if-else` choice *inside* your JSX. It is a JavaScript expression, so it evaluates to a value and is perfectly valid inside ``.
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <Dashboard /> : <LoginPage />}
</div>
);
}Pattern 2: Logical AND (`&&`)
Use this when you want to render something *or nothing*. In JavaScript, `true && expression` evaluates to `expression`, and `false && expression` evaluates to `false`. React ignores `false` and renders nothing.
function Mailbox({ unreadMessages }) {
return (
<div>
{unreadMessages.length > 0 && <h2>You have mail!</h2>}
</div>
);
}⚠️ Pitfall: The `0` Problem
`0` is a falsy value. So 0 && >Component /< short-circuits and evaluates to `0`. Unlike `false`, React actually renders the number 0! Always use a boolean check like `count > 0`.
Pattern 3: Logical OR (`||`)
Perfect for default or fallback values. If the left side is falsy (like `null` or `undefined`), it renders the right side.
<h1>Hello, {user.name || 'Guest'}</h1>Pattern 4: Element Variables+
If logic is too complex for ternaries, use a variable and standard `if/else` *before* the return statement.
let content;
if (status === 'submitting') content = <Spinner />;
else if (status === 'error') content = <ErrorIcon />;
else content = <SubmitButton />;
return <div>{content}</div>;