Conditional Rendering in React: 5 Patterns with Runnable Examples
Learn when to use early returns, ternaries, logical AND, null, and switch through a course dashboard you can run and test with five UI states.
KnowledgeGate Team
Exam prep & CS education

JSX can show a fixed heading easily. A real interface must choose among loading, error, signed-out, in-progress, and completed states. Conditional rendering uses ordinary JavaScript to select the element tree, text value, or null for the current state.
Conditional rendering in React: the decision before the JSX
Conditional rendering means choosing which React element tree, text value, or null a component returns for its current props and state. Start with const isLoggedIn = false. The expression isLoggedIn ? <Dashboard /> : <Login /> chooses Login. Change the value to true, and the same expression chooses Dashboard.
Keep three decisions separate. Replace a whole screen with an early return. Choose between two inline elements with a ternary. Add one optional element with logical &&. For three or more named states, use a switch or a helper component. This distinction is useful throughout a web-development learning path. It is different from hiding an element with CSS, because that element still exists in the rendered tree.
Choose among five patterns without nesting a puzzle
Use the form that makes every possible UI state obvious at a glance.
Pattern | Best use |
|---|---|
| Mutually exclusive page states |
| Exactly two visible outcomes |
| One optional addition |
| A component should contribute no UI |
| Three or more named states |
These tools produce values React renders. If score = 72, then score >= 40 ? "Pass" : "Retry" returns "Pass". If isNew = true, isNew && <span>New</span> renders the badge. If isNew = false, it adds no badge. Avoid nested ternaries for a multi-state dashboard because their order is hard to check.
Worked example: render five exact CourseDashboard states
Run this component with Asha's default mid-course data.
function CourseDashboard({ isLoading, error, learner }) {
if (isLoading) return <p>Loading your dashboard...</p>;
if (error) return <p role="alert">{error}</p>;
if (!learner) return <button>Log in to continue</button>;
const remaining = learner.totalLessons - learner.completedLessons;
return (
<section>
<h2>Welcome, {learner.name}</h2>
<p>{learner.completedLessons} of {learner.totalLessons} lessons completed</p>
{remaining > 0
? <button>Continue: {learner.nextLesson}</button>
: <strong>Course complete</strong>}
{learner.hasCertificate && <button>Download certificate</button>}
</section>
);
}
const asha = {
name: "Asha",
completedLessons: 3,
totalLessons: 5,
nextLesson: "React Lists",
hasCertificate: false
};
export default function App() {
return <CourseDashboard isLoading={false} error={null} learner={asha} />;
}For Asha, remaining = 5 - 3 = 2. The output is Welcome, Asha, 3 of 5 lessons completed, and Continue: React Lists, with no certificate button. The first three early returns keep loading, error, and guest branches out of the main JSX.
Check four replacements. isLoading={true} shows only Loading your dashboard.... With loading false, error="Could not load progress" shows only that alert. With no error, learner={null} shows only Log in to continue. Kabir with completedLessons: 5, totalLessons: 5, nextLesson: null, and hasCertificate: true has remaining = 5 - 5 = 0. He sees Welcome, Kabir, 5 of 5 lessons completed, Course complete, and Download certificate.

Ternary and logical AND inside one rendered branch
Asha has remaining = 2. A ternary suits the action because the interface must show either Continue: React Lists or Course complete, never both. Keep its branches aligned, and extract them if either grows beyond one small element.
Logical && is an optional addition, not an either-or choice. Asha's false value adds no certificate button. Kabir's true value adds Download certificate after Course complete.
Element choice still matters: use a real button for an action and role="alert" for this error message, not a clickable div.

Return null or use switch when the branch shape changes
Use null when a component should contribute no UI for a render:
function PromoBanner({ eligible }) {
if (!eligible) return null;
return <aside>New course available</aside>;
}With eligible = false, PromoBanner contributes no UI. With eligible = true, the banner appears. It is unmounted only if its parent stops rendering it.
For named states, a switch keeps every outcome explicit:
function SaveMessage({ status }) {
switch (status) {
case "saving": return <p>Saving profile...</p>;
case "saved": return <p>Profile saved</p>;
case "error": return <p role="alert">Save failed. Try again.</p>;
default: return null;
}
}The inputs "saving", "saved", and "error" produce those messages. "idle" or an unknown value produces no UI. One status is safer than contradictory booleans such as isSaving = true and hasError = true.
Common errors: visible zeroes, conditional hooks and unreadable branches
A number needs an explicit Boolean check. With unreadCount = 0, this expression evaluates to 0, which React can display:
{unreadCount && <p>{unreadCount} unread</p>}Use {unreadCount > 0 && <p>{unreadCount} unread</p>} instead. With unreadCount = 0, it adds nothing. With unreadCount = 4, it displays 4 unread.
Do not call a Hook conditionally:
if (learner) {
const [tab, setTab] = useState("overview");
}Call const [tab, setTab] = useState("overview") at the component's top level, then make only the returned JSX conditional. This preserves the same Hook call order on every render. The React Hooks guide owns state, effects, memoisation, and custom hooks; this tutorial owns the rendering branches that consume their values.
Replace loading ? A : error ? B : learner ? C : D with named early returns. Replace impossible Boolean combinations with one status such as "loading" | "error" | "guest" | "ready". Also remember that an if statement cannot sit directly inside JSX braces, because JSX expects an expression there.
Exercises and interview-style output checks
Build
NotificationBadge({ unreadCount }). Input0must render nothing, while input4must render4 unread. Use theunreadCount > 0guard, so no visible0can leak into the page.Build
TrafficLight({ status })with aswitch:"red"givesStop,"amber"givesWait,"green"givesGo, and any other value givesUnknown signal. Exactly one label should appear for each input.Extend
CourseDashboardwithrole = "student" | "instructor". A student seesContinue: React Lists, an instructor seesEdit course, and any other role seesView course. Keep Asha at 3 of 5 lessons so only the role decision changes, and render exactly one course action.
Predict two more outputs. If loading is true and an error string also exists, Loading your dashboard... wins because its early return comes first. If a component's condition fails and it explicitly returns null, that component contributes no UI for the render.
The short version and the next study step
Use an early return for whole states, a ternary for A-or-B, && for an optional element after converting numeric conditions to Booleans, null for no UI, and a switch or helper for named multi-state logic. In the dashboard, precedence is loading, error, guest, then ready. For guided React and Redux practice, see the React and Redux Course. To place React inside a full-stack project path, explore the MERN Stack Course.
Keep learning
useContext in React: A Practical Tutorial with Runnable Examples
Build shared React preferences without prop drilling. Follow complete JSX examples, provider behaviour, and output questions.
React Events Tutorial: onClick, Forms and Runnable Examples
Build one PracticeTracker component, follow every click, change and submit, then learn exactly when to use preventDefault and stopPropagation.
Testing React Components: A Runnable Vitest and Testing Library Tutorial
Build and test a small React progress component from its initial render through completion. The examples use accessible queries, awaited actions, and an exact mock assertion.
useReducer in React: Build Predictable State with Runnable Examples
Learn when a reducer makes React state clearer. Build a score reducer and a complete study-task app, then verify every transition and test the reducer without a browser.





