Conditional Rendering
Your components often need to display different content based on conditions. In React, you can conditionally render JSX using JavaScript syntax likeif statements, &&, and ternary operators.
Conditionally Returning JSX
The simplest way to conditionally render is to return early:Returning Nothing
Returnnull to render nothing:
Important: Returning
null, undefined, true, or false from a component renders nothing. However, these values behave differently inside JSX expressions.Ternary Operator
Use the ternary operator (? :) for inline conditional rendering:
Nested Ternaries
Readability tip: Deeply nested ternaries can be hard to read. Consider using
if statements or extracting logic into a function if you have more than 2 levels.Logical AND Operator (&&)
Use&& to render something only when a condition is true:
How && Works in JSX
Gotcha: The left side of
&& is rendered if it’s a falsy number like 0. Always use boolean conditions:- ✅
isReady && <Component /> - ✅
count > 0 && <Component /> - ❌
count && <Component />(renders 0 when count is 0)
If/Else in JSX
You can’t useif/else directly in JSX, but you can use it before the return:
Using IIFE (Immediately Invoked Function Expression)
Multiple Conditions
Handle complex conditional logic with multiple conditions:Conditional Attributes
Conditionally set element attributes:Conditional Class Names
Extracting Conditional Logic
For complex conditions, extract into helper functions:Conditional Rendering with State
Combine conditional rendering with state for interactive UIs:Complete Authentication Example
import { useState } from 'react';
function AuthPage() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [user, setUser] = useState(null);
const handleLogin = async (credentials) => {
setIsLoading(true);
setError(null);
try {
const response = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify(credentials)
});
if (!response.ok) throw new Error('Login failed');
const userData = await response.json();
setUser(userData);
setIsLoggedIn(true);
} catch (err) {
setError(err.message);
} finally {
setIsLoading(false);
}
};
// Show loading state
if (isLoading) {
return (
<div className="auth-page">
<div className="spinner">Loading...</div>
</div>
);
}
// Show logged in state
if (isLoggedIn && user) {
return (
<div className="auth-page">
<h1>Welcome, {user.name}!</h1>
<p>Email: {user.email}</p>
{user.isAdmin && (
<div className="admin-badge">Admin Access</div>
)}
<button onClick={() => setIsLoggedIn(false)}>
Logout
</button>
</div>
);
}
// Show login form
return (
<div className="auth-page">
<h1>Login</h1>
{error && (
<div className="error-message">{error}</div>
)}
<LoginForm onSubmit={handleLogin} />
</div>
);
}
Pattern Comparison
Choose the right pattern for your use case:Best Practices
Guidelines for conditional rendering:
- Use early returns for component-level conditions
- Use
&&for simple show/hide logic (with boolean conditions) - Use ternary for either/or scenarios
- Extract complex conditions into helper functions
- Avoid deeply nested ternaries
- Be careful with falsy values (especially
0) with&&