Conditional Rendering in React
# Conditional Rendering in React
1. Introduction
In standard HTML, everything you write is sent to the browser and displayed. But in dynamic applications, you rarely want to show everything at once. You want to show a "Logout" button *only* if the user is logged in. You want to show an "Error" banner *only* if something went wrong. In React, deciding what to show based on data is called Conditional Rendering.2. Learning Objectives
By the end of this chapter, you will be able to:- Render JSX elements based on boolean conditions.
-
Use the Ternary Operator (
condition ? true : false) inside JSX.
-
Use Logical AND (
&&) for short-circuit rendering.
-
Understand when to use early
returnstatements for entire components.
3. Beginner-Friendly Explanations
What is Conditional Rendering?
Conditional rendering in React works exactly the same way conditions work in standard JavaScript. You use logic (if, else, ternary operators) to create components representing the current state, and React updates the UI to match them.
Because JSX is just JavaScript under the hood, we can inject logic right in the middle of our HTML tags using curly braces {}.
4. Syntax Explanation & Approaches
Approach 1: Early Return (If Statements)
If an entire component should look completely different based on a condition, you can use a standardif statement before the final return.
```jsx id="ch9_ex1" // Example React component function Greeting({ isLoggedIn }) { if (isLoggedIn) { return <h1>Welcome back, user!</h1>; } // If the 'if' block runs, it returns early and this code never runs. return <h1>Please sign up or log in.</h1>; }
jsx id="ch9_ex2" // Example React component function LoginButton({ isLoggedIn }) { return ( <div className="navbar"> <span>MyLogo</span> {/* Condition inside JSX! */} {isLoggedIn ? ( <button>Logout</button> ) : ( <button>Login</button> )} </div> ); }
jsx id="ch9_ex3" // Example React component function Notification({ hasUnreadMessages, unreadCount }) { return ( <div> <h2>Inbox</h2> {/* Only render the badge if hasUnreadMessages is true */} {hasUnreadMessages && ( <span className="badge">You have {unreadCount} new messages!</span> )} </div> ); }
jsx id="ch9_proj1" // Example React component import React, { useState } from 'react';
export default function AuthHeader() { // Simulate user authentication state const [isLoggedIn, setIsLoggedIn] = useState(false);
// Helper functions for events const handleLogin = () => setIsLoggedIn(true); const handleLogout = () => setIsLoggedIn(false);
return ( <header className="bg-white shadow-md p-4 flex justify-between items-center max-w-4xl mx-auto rounded-b-lg"> <div className="font-black text-2xl tracking-tighter text-indigo-600"> LogoBrand </div>
<div className="flex items-center gap-4"> {/* Logical && for an admin badge (simulated as always false here for example, but imagine it's a prop) */} {/* {isAdmin && <span className="bg-purple-100 text-purple-700 px-2 py-1 text-xs rounded font-bold">Admin</span>} */}
{/* Ternary operator for the UI toggle */}
{isLoggedIn ? (
<div className="flex items-center gap-4">
<span className="text-gray-600 font-medium">Welcome, Developer!</span>
<button
onClick={handleLogout}
className="bg-gray-100 hover:bg-gray-200 text-gray-800 px-4 py-2 rounded-lg font-medium transition"
>
Log Out
</button>
</div>
) : (
<div className="flex gap-2">
<button className="text-gray-600 hover:text-indigo-600 font-medium px-4 py-2 transition">
Sign In
</button>
<button
onClick={handleLogin}
className="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-lg font-medium shadow-sm transition"
>
Create Account
</button>
</div>
)}
</div>
</header>
);
}
``
11. Coding Challenges
Challenge 1: Write a WeatherDisplay component with an isRaining prop. Render an Umbrella icon (or text) if true, and a Sun icon if false.
12. MCQs with Answers
Q1: Which operator is best used for conditionally rendering an element when there is NO "else" condition?
A) ? : (Ternary)
B) && (Logical AND)
C) || (Logical OR)
D) ! (NOT)
*Answer: B*
Q2: Why can't we use a standard
if/else statement directly inside the {} of JSX?
A) JSX only accepts React Components inside curly braces.
B) if/else are JavaScript statements, and JSX requires expressions that evaluate to a value.
C) React deprecates if blocks for performance reasons.
*Answer: B*
13. Interview Questions
-
Q: What is the risk of using
{array.length && <Component />}? *(Answer: If length is 0, React renders a '0' to the DOM. Use array.length > 0 instead).*
-
Q: Describe three ways to conditionally render elements in React.
14. FAQs
Can I nest ternary operators?
Yes, condition1 ? UI1 : condition2 ? UI2 : UI3. However, doing this inside JSX makes the code very hard to read. If you have complex logic, extract it into a helper function above your return statement.
15. Summary
Conditional rendering is how you bring business logic into your UI. By utilizing early returns, the ternary operator (? :), and logical AND (&&`), you can easily toggle the visibility of components based on state or props, creating rich, dynamic user experiences.