Conditional Rendering
Show different UI based on conditions using if, ternary or &&.
Syntax
{isLoggedIn ? <Dashboard /> : <Login />}Because components are just JavaScript, you render UI conditionally with normal JavaScript logic.
Three common patterns
- if / early return — decide before the JSX.
- Ternary
condition ? a : b— choose between two outputs inline. - Logical AND
condition && jsx— render something only when true.
Example
function Status({ user, unread }) {
if (!user) {
return <p>Please log in.</p>;
}
return (
<div>
<p>Welcome back, {user.name}!</p>
{unread > 0 && <p>You have {unread} new messages.</p>}
</div>
);
}When to use it
- An e-commerce cart shows a checkout button only when at least one item is in the cart, using the && short-circuit pattern to hide it when the array is empty.
- A dashboard displays either a loading spinner or a data table depending on whether the fetch has completed, using a ternary expression in JSX.
- An authentication flow renders a login form for unauthenticated users and a profile page for authenticated ones via an early-return guard at the top of the component.
More examples
Early return guard
Uses an early return to bail out of rendering before the main JSX when data is absent.
function UserPanel({ user }) {
if (!user) {
return <p>Please log in.</p>;
}
return (
<div className="panel">
<h2>Welcome, {user.name}</h2>
</div>
);
}Ternary for two outcomes
Uses the ternary operator inside JSX to choose between two components based on a boolean flag.
function LoadingOrContent({ isLoading, data }) {
return (
<main>
{isLoading
? <Spinner />
: <DataTable rows={data} />}
</main>
);
}Short-circuit && rendering
Demonstrates the && pattern to conditionally render an element only when a condition is truthy.
function Cart({ items }) {
return (
<div>
<h2>Cart</h2>
{items.length > 0 && (
<button className="btn-checkout">Checkout ({items.length})</button>
)}
{items.length === 0 && <p>Your cart is empty.</p>}
</div>
);
}
Discussion