What are the ways to do conditional rendering in React?
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
Ternaries for either/or output, && for render-or-nothing, early returns for whole branches, variables/ifs for complex logic — plus element variables and returning null to render nothing.
Detailed explanation
JSX is just expressions, so any JavaScript condition works. The ternary operator handles two-branch rendering inline. Logical && renders something only when the left side is truthy — with one famous trap: a numeric left side like {count && <Badge/>} renders literal 0 when count is zero, because 0 is falsy but still rendered; guard with count > 0 && instead. Early returns inside the component keep complex conditions readable before JSX starts. For multi-branch UIs, assigning the chosen element to a variable keeps markup clean. Switching entire screens usually belongs at the routing level rather than conditionals. Whatever the technique, prefer readability: nested ternaries inside JSX are where bugs hide.
Official docs:React docs: Conditional Rendering
Example
function Banner({ user, error }) {
if (error) return <Alert type="error">{error}</Alert>;
if (!user) return null;
return user.isAdmin ? (
<AdminPanel user={user} />
) : (
<>
Welcome back{user.unread > 0 && <Badge count={user.unread} />}
</>
);
}Interview tip
Cover ternary, &&, and early return quickly, then volunteer the {0 && ...} renders-zero gotcha — it's a favorite follow-up probe.
Common mistakes
- Using
x && <Y/>where x can be 0 or NaN. - Nesting ternaries three levels deep inside JSX.