Conditional rendering in React allows components to display different markup depending on current state, props, or permissions.
null or placeholder elements before rendering main markup.condition ? true : false): Choose between two alternative UI branches inside JSX.condition && <Element />): Render an element only when a condition is met.flowchart TD
State["Component State"] --> Check{"User Authenticated?"}
Check -- Yes --> Dashboard["Render <UserDashboard />"]
Check -- No --> Login["Render <LoginForm />"]
import React, { useState } from 'react';
function LoadingSpinner() {
return <div className="spinner">Loading data...</div>;
}
export default function AccountOverview({ isLoading, user, unreadCount }) {
// 1. Guard Clause: Early Return while loading
if (isLoading) {
return <LoadingSpinner />;
}
// 2. Guard Clause: Handle null data state
if (!user) {
return <div className="error">No user session found. Please log in.</div>;
}
return (
<div className="account-card">
<h2>Welcome, {user.name}</h2>
{/* 3. Ternary Operator for Status Badge */}
<span className={user.isPremium ? 'badge-gold' : 'badge-silver'}>
{user.isPremium ? 'Premium Account' : 'Free Tier'}
</span>
{/* 4. Logical AND Operator for Optional Notifications */}
{unreadCount > 0 && (
<div className="notification-pill">
You have {unreadCount} unread messages.
</div>
)}
</div>
);
}
&&: In JavaScript, 0 && <Component /> evaluates to 0, rendering a literal 0 on the screen! To prevent this, convert numbers to explicit booleans: unreadCount > 0 && <Component /> or Boolean(unreadCount) && <Component />.return statement.Refactor a component that displays "Admin View" if role === 'admin', "Editor View" if role === 'editor', and "Guest View" for all others using a clean JavaScript switch statement or lookup dictionary.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.