React
Beginner
1 min read
Conditional Rendering with Ternary and &&
Example
import { useState } from 'react';
function StatusBadge({ status }) {
// Multi-branch: object lookup is cleaner than nested ternaries
const config = {
loading: { label: 'Loading…', bg: '#fef9c3' },
success: { label: 'Success', bg: '#dcfce7' },
error: { label: 'Error', bg: '#fee2e2' },
idle: { label: 'Idle', bg: '#f3f4f6' },
};
const { label, bg } = config[status] ?? config.idle;
return <span style={{ background: bg, padding: '2px 10px', borderRadius: 12 }}>{label}</span>;
}
function Dashboard() {
const [status, setStatus] = useState('idle');
const [count, setCount] = useState(0);
const [isAdmin, setIsAdmin] = useState(false);
return (
<div>
{/* Ternary: one of two outputs */}
<p>{isAdmin ? '🔐 Admin view' : '👤 User view'}</p>
<button onClick={() => setIsAdmin(a => !a)}>Toggle admin</button>
{/* && with boolean guard (avoid count && to prevent rendering "0") */}
{count > 0 && <p>You have {count} notification(s)</p>}
<button onClick={() => setCount(c => c + 1)}>Add notification</button>
{/* Multi-branch status badge */}
<div style={{ marginTop: 12 }}>
<StatusBadge status={status} />
<div style={{ marginTop: 8 }}>
{['idle', 'loading', 'success', 'error'].map(s => (
<button key={s} onClick={() => setStatus(s)} style={{ marginRight: 4 }}>{s}</button>
))}
</div>
</div>
</div>
);
}
export default Dashboard;