"React is just like life: sometimes you show up, sometimes you don't. Depends on the condition."
Ever wanted to show different components based on user login status or whether data is loaded? That's where conditional rendering comes in!
What Is Conditional Rendering?
Conditional rendering is when you decide what to render based on a certain condition. It's a core concept in React — allowing your UI to respond dynamically to changes.
Common Techniques for Conditional Rendering
1. if Statement (outside JSX)
function Welcome({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
} else {
return <h1>Please log in.</h1>;
}
}
2. JSX Variable Assignment
function Greeting({ isMorning }) {
let message;
if (isMorning) {
message = <h2>Good Morning!</h2>;
} else {
message = <h2>Good Evening!</h2>;
}
return <div>{message}</div>;
}
3. Ternary Operator (? :)
function Status({ isOnline }) {
return (
<p>
Status: {isOnline ? <span style={{color: 'green'}}>Online</span> : <span style={{color: 'gray'}}>Offline</span>}
</p>
);
}
4. Logical AND (&&)
function Profile({ isLoggedIn }) {
return (
<div>
<h1>Welcome!</h1>
{isLoggedIn && <button>Logout</button>}
</div>
);
}
5. Nested Ternaries (use cautiously)
function Weather({ condition }) {
return (
<p>
{condition === 'sunny' ?: condition === 'rainy' ? '🌧️' : '❓'}
</p>
);
}
6. switch Statement
function Message({ type }) {
let content;
switch (type) {
case 'success':
content = <p style={{color: 'green'}}>Success!</p>;
break;
case 'error':
content = <p style={{color: 'red'}}>Error!</p>;
break;
default:
content = <p>Unknown status</p>;
}
return content;
}
7. Custom If Component
function If({ condition, children }) {
return condition ? children : null;
}
Real World Example: Login Form
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
<h1>React Conditional Rendering</h1>
{isLoggedIn ? (
<div>
<p>Welcome, User!</p>
<button onClick={() => setIsLoggedIn(false)}>Logout</button>
</div>
) : (
<div>
<p>Please log in to continue.</p>
<button onClick={() => setIsLoggedIn(true)}>Login</button>
</div>
)}
</div>
);
}
Combined with useState
function ToggleDetails() {
const [showDetails, setShowDetails] = useState(false);
return (
<div>
<button onClick={() => setShowDetails(prev => !prev)}>
{showDetails ? 'Hide' : 'Show'} Details
</button>
{showDetails && <p>This is some hidden content!</p>}
</div>
);
}
Best Practices
- Use ternary for short conditions only
- Move complex logic out of JSX
- Modularize into separate components if necessary
- Watch out for rendering 0, null, or false unintentionally
Common Mistakes
- Deeply nested ternary operators
- Forgetting return in if-else
- Rendering unintended falsy values
- Overloading JSX with logic
Loading Spinner
function DataFetcher() {
const [loading, setLoading] = useState(true);
useEffect(() => {
setTimeout(() => setLoading(false), 3000);
}, []);
return (
<div>
{loading ? <p>Loading...</p> : <p>Data is ready!</p>}
</div>
);
}
Conditional rendering is a core skill in React development. Use it wisely to make your UI responsive, dynamic, and clean.
"React without conditional rendering is like Netflix with only one show."
0 Comments:
Post a Comment