React Conditional Rendering
Learn to show or hide content based on conditions - if statements, ternary operators, and logical AND.
Conditional Rendering means showing different things based on conditions - like showing a login button if user is not logged in.
What is Conditional Rendering?
Show or hide elements based on:
- User logged in or not - Loading state - Error messages - Empty data - User permissions
Using if Statement
```javascript function Greeting() { const isLoggedIn = true;
if (isLoggedIn) { return <h1>Welcome back!</h1>; } else { return <h1>Please log in</h1>; } } ```
Using Ternary Operator (? :)
This is more common in React:
```javascript function Greeting() { const isLoggedIn = true;
return ( <div> {isLoggedIn ? ( <h1>Welcome back!</h1> ) : ( <h1>Please log in</h1> )} </div> ); } ```
**Format:** `condition ? ifTrue : ifFalse`
Logical AND (&&)
Show something only if condition is true:
```javascript function Notifications() { const hasMessages = true;
return ( <div> <h1>Dashboard</h1> {hasMessages && <p>You have new messages!</p>} </div> ); } ```
If `hasMessages` is false, nothing shows. If true, the message shows!
Showing/Hiding with State
```javascript function App() { const [isVisible, setIsVisible] = useState(true);
return ( <div> <button onClick={() => setIsVisible(!isVisible)}> Toggle </button>
{isVisible && ( <div> <h2>Secret Content!</h2> <p>You can see this only when visible!</p> </div> )} </div> ); } ```
Loading States
Show loading message while fetching data:
```javascript function UserProfile() { const [isLoading, setIsLoading] = useState(true); const [user, setUser] = useState(null);
return ( <div> {isLoading ? ( <p>Loading user data...</p> ) : ( <div> <h2>{user.name}</h2> <p>{user.email}</p> </div> )} </div> ); } ```
Error Messages
```javascript function LoginForm() { const [error, setError] = useState('');
const handleLogin = () => { if (password.length < 6) { setError('Password too short!'); } else { setError(''); // Login user } };
return ( <div> <input type="password" /> <button onClick={handleLogin}>Login</button>
{error && <p style={{color: 'red'}}>{error}</p>} </div> ); } ```
Multiple Conditions
```javascript function StatusMessage({ status }) { return ( <div> {status === 'loading' && <p>Loading...</p>} {status === 'success' && <p>Success! ✓</p>} {status === 'error' && <p>Error occurred! ✗</p>} </div> ); } ```
Empty State
Show message when list is empty:
```javascript function TodoList() { const todos = [];
return ( <div> <h2>My Todos</h2>
{todos.length === 0 ? ( <p>No todos yet! Add your first task.</p> ) : ( <ul> {todos.map((todo, index) => ( <li key={index}>{todo}</li> ))} </ul> )} </div> ); } ```
Conditional CSS Classes
Apply different styles based on conditions:
```javascript function Button({ isPrimary }) { const className = isPrimary ? 'btn-primary' : 'btn-default';
return <button className={className}>Click Me</button>; } ```
Or inline:
```javascript function Alert({ isWarning }) { return ( <div style={{ backgroundColor: isWarning ? 'yellow' : 'green', color: isWarning ? 'red' : 'white' }}> Alert Message </div> ); } ```
Complete Example - User Dashboard
```javascript function Dashboard() { const [isLoggedIn, setIsLoggedIn] = useState(false); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState('');
const handleLogin = () => { setIsLoading(true); // Simulate login setTimeout(() => { setIsLoading(false); setIsLoggedIn(true); }, 2000); };
return ( <div> {isLoading && <p>Logging in...</p>}
{error && <p style={{color: 'red'}}>{error}</p>}
{!isLoggedIn ? ( <div> <h2>Please Login</h2> <button onClick={handleLogin}>Login</button> </div> ) : ( <div> <h2>Welcome to Dashboard!</h2> <p>You are now logged in</p> <button onClick={() => setIsLoggedIn(false)}> Logout </button> </div> )} </div> ); } ```
When to Use What
**If/Else Statement:** Complex logic, multiple lines
**Ternary Operator (? :):** Choose between two options
**Logical AND (&&):** Show something or nothing
**Multiple &&:** Show different things based on different conditions
Common Patterns
### Show/Hide Button
```javascript {isEditing ? ( <button onClick={handleSave}>Save</button> ) : ( <button onClick={handleEdit}>Edit</button> )} ```
### Feature Flag
```javascript const showNewFeature = true;
{showNewFeature && <NewFeatureComponent />} ```
### Permission Check
```javascript {user.isAdmin && <AdminPanel />} ```
Remember
- Use `? :` for if-else (two options) - Use `&&` for showing/hiding (one option) - Always handle loading states - Show clear error messages - Handle empty states - Keep conditions simple and readable
> Congratulations! You've completed the React basics! Now you can build interactive React applications. Keep practicing and building projects!