React Conditionals
What Are React Conditionals?
Conditional rendering in React is the process of displaying different UI elementsΒ or nothing at all depending on certain conditions (state, props, or logic). React does not have special template directives for conditionals (like Angular’s
*ngIf); instead, it leverages plain JavaScript conditional expressions directly inside JSX.Imagine your 7Scribes LMS: a student who is not logged in sees a login screen, but a student who is logged in sees their course dashboard. That entire UI switch is controlled by conditional rendering. It is one of the most fundamental concepts in React.
Because JSX is just JavaScript, you can use any JavaScript technique to conditionally render contentΒ if/else, ternary operators, logical operators, switch statements, and more. Each technique has its own strengths and ideal use cases.
React Conditional Rendering
Complete cheatsheet: if/else, ternary, &&, ||, ??, switch, IIFE, and component patterns with inline examples.
| Pattern | Code Snippet / Example | When to use / Tip |
|---|---|---|
|
Β if / else (before return)
|
|
Classic pattern
Best for complex logic outside JSX. Full control, avoids inline clutter.
|
|
Early return
|
|
Guard clause
Prioritise error/loading states. Keeps core rendering clean.
|
|
Ternary Operator
|
|
Recommended
Inline A-or-B rendering. Perfect for simple branching inside JSX.
|
|
Logical AND (&&)
|
|
Show/hide
Show-or-nothing pattern. Avoid falsy values like 0 β always use comparison.
|
|
Logical OR (||)
|
|
Fallback
Renders fallback when left side is falsy (0, “”, false, null, undefined).
|
|
Nullish Coalescing (??)
|
|
Safer
Fallback only for
null / undefined. Perfect for numbers / empty strings. |
|
Switch Statement
|
|
Multiple states
Ideal for 3+ discrete states (role, status, theme).
|
|
Render null
|
|
Hide component
Conditionally render nothing, component unmounts in React.
|
