react · source-driven
Conditional rendering
React has no special template if-syntax. Use ordinary JavaScript: if, ternary, and &&.
Official docs: react.dev/learn — Conditional rendering
You will learn
- How to use if/else before return
- How to use the ternary ? : inside JSX
- How to use && when there is no else branch
Use the same techniques as regular JavaScript
From the docs — compute with if:
let content;
if (isLoggedIn) {
content = <AdminPanel />;
} else {
content = <LoginForm />;
}
return <div>{content}</div>;Or ternary inside JSX:
{isLoggedIn ? <AdminPanel /> : <LoginForm />}Or && when you only care about the true branch:
{isLoggedIn && <AdminPanel />}Try it
Login form (else branch)
Ternary: LoginForm
&&:
Recap
- No special React if-syntax — use JavaScript
- Ternary works inside JSX; if does not (unless before return)
- && is for “render this or nothing”
Challenge
Try this
Render a status badge that shows “open” in teal when status === 'open', otherwise “done” in gray — using a ternary on style or on the text.