function Status({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>}
</div>
);
}The pattern condition ? ifTrue : ifFalse is the standard way to choose between exactly two pieces of JSX to render.
function Notifications({ count }) {
return (
<div>
<h3>Inbox</h3>
{count > 0 && <p>You have {count} new messages</p>}
</div>
);
}condition && <JSX /> renders the JSX only when the condition is true, and renders nothing at all when it's false โ perfect for optional content like badges or warning banners.
function UserList({ loading, error, users }) {
if (loading) return <p>Loading...</p>;
if (error) return <p>Something went wrong.</p>;
if (users.length === 0) return <p>No users found.</p>;
return (
<ul>
{users.map(u => <li key={u.id}>{u.name}</li>)}
</ul>
);
}Using early return statements for each distinct state (loading, error, empty, success) keeps a component's main render logic clean, rather than nesting several ternaries inside one another.
Writing {count && <p>...</p>} when count could be 0 has a sneaky bug: since 0 is falsy, React actually renders the literal number 0 on the page (because 0 && anything evaluates to 0, and React renders numbers). Fix it by explicitly comparing: {count > 0 && <p>...</p>}.
Write a component that shows "Loading...", an error message, or a list of items depending on three boolean/array props, using early returns.
function ItemList({ loading, error, items }) {
if (loading) return <p>Loading...</p>;
if (error) return <p>Failed to load items.</p>;
return (
<ul>
{items.map((item, i) => <li key={i}>{item}</li>)}
</ul>
);
}
Q Which is better: ternary or &&?
Use && when you only need to show something or nothing (one-sided). Use a ternary when you're choosing between two different pieces of JSX to display โ both are equally valid, standard React patterns.
Q Can I use a regular if statement directly inside the JSX return?
Not directly inside curly braces, since if is a statement, not an expression. You can use if statements above the return (as shown with early returns), or use a ternary/&& inside the JSX itself.