Conditional Rendering in React
Imagine you have a user profile page. If the user is logged in, you want to show their name and picture. If they're not logged in, you want to show a login button. This is called **conditional rendering** – showing different UI based on different conditions.
What is Conditional Rendering?
Conditional rendering in React works the same way conditions work in JavaScript. You use JavaScript operators like `if` statements or ternary operators to create elements representing the current state, and React updates the UI to match them.
In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application.
Method 1: If-Else Outside JSX
function Greeting({ isLoggedIn }) { if (isLoggedIn) { return <h1>Welcome back!</h1>; } else { return <button>Login</button>; }}This is the simplest approach. You use a regular `if-else` statement outside the JSX to decide what to return.
Method 2: Ternary Operator (Most Common)
function Greeting({ isLoggedIn }) { return ( <div> {isLoggedIn ? ( <h1>Welcome back!</h1> ) : ( <button>Login</button> )} </div> );}The ternary operator (`condition ? true : false`) is perfect for inline conditional rendering inside JSX.
Method 3: Logical && Operator
function Notification({ messages }) { return ( <div> {messages.length > 0 && ( <div> You have {messages.length} unread messages. </div> )} </div> );}The `&&` operator is great for rendering something only when a condition is true. If the condition is false, React ignores and doesn't render the element.
Method 4: Switch Statement with Function
function UserStatus({ status }) { function getStatusMessage() { switch (status) { case 'active': return <span style={{ color: 'green' }}>Active</span>; case 'inactive': return <span style={{ color: 'gray' }}>Inactive</span>; case 'banned': return <span style={{ color: 'red' }}>Banned</span>; default: return <span>Unknown</span>; } }
return <div>Status: {getStatusMessage()}</div>;}For multiple conditions, a `switch` statement can make your code cleaner.
Real-World Example: User Dashboard
function Dashboard() { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null);
<!-- Simulating data fetch --> useEffect(() => { fetchUser() .then(data => { setUser(data); setLoading(false); }) .catch(err => { setError(err); setLoading(false); }); }, []);
if (loading) { return <div>Loading dashboard...</div>; }
if (error) { return <div>Error loading dashboard: {error.message}</div>; }
if (!user) { return <button>Login</button>; }
return ( <div> <h1>Welcome, {user.name}!</h1> {user.isAdmin && <AdminPanel />} <div> {user.notifications.length > 0 ? ( <NotificationList notifications={user.notifications} /> ) : ( <p>No new notifications</p> )} </div> </div> );}Two Minute Drill
- Conditional rendering means showing different UI based on conditions (like user login state, loading status, etc.).
- if-else: Use outside JSX for simple conditional returns.
- Ternary operator: Use inside JSX for if-else conditions.
- && operator: Use inside JSX when you want to render something OR nothing.
- Switch statement: Use for multiple conditions with a function returning JSX.
- Conditional rendering makes your apps dynamic and responsive to different states.
Need more clarification?
Drop us an email at career@quipoinfotech.com
