Chapter 2 of 4
Conditional Rendering
Ternaries, logical AND, early returns and when to use each.
There is no special syntax for conditionals in JSX. You use ordinary JavaScript, and pick whichever form reads best.
Ternary: one of two things
function Status({ isOnline }) {
return <span>{isOnline ? "Online" : "Offline"}</span>;
}Logical AND: show it or show nothing
function Inbox({ unreadCount }) {
return (
<div>
<h2>Inbox</h2>
{unreadCount > 0 && <p>{unreadCount} unread messages</p>}
</div>
);
}Early return: skip the whole component
When a component should render nothing, or something entirely different, return early. It keeps the main path free of nesting.
function UserProfile({ user, isLoading, error }) {
if (isLoading) return <Spinner />;
if (error) return <ErrorMessage error={error} />;
if (!user) return null;
return (
<section>
<h2>{user.name}</h2>
<p>{user.bio}</p>
</section>
);
}Choosing between many options
For more than two or three branches, an object lookup is usually clearer than nested ternaries.
const STATUS_LABELS = {
pending: <Badge tone="warning">Pending</Badge>,
shipped: <Badge tone="info">Shipped</Badge>,
delivered: <Badge tone="success">Delivered</Badge>,
};
function OrderStatus({ status }) {
return STATUS_LABELS[status] || <Badge>Unknown</Badge>;
}