Fundamentals
Conditional Rendering
Master conditional rendering in React, covering if/else blocks, ternary operators, logical AND (&&) shortcuts, and returning null.
1. Learning Objectives
In this lesson, you will learn how to render different UI structures based on state or props. By the end of this topic, you will be able to:
- Apply conditional rendering using standard
if/elsestatements. - Write clean conditional templates using the Ternary Operator (
? :). - Use the Logical AND operator (
&&) for inline conditional checks. - Avoid rendering numbers (like
0) when using the logical AND operator. - Return
nullto prevent a component from rendering anything in the DOM.
2. Overview
In React, conditional rendering works the same way conditions work in JavaScript. You can use JavaScript operators like if, `switch`, ternary operators, or logical shortcuts to describe which elements should be rendered based on the current state or props of the component.
3. Why This Topic Matters
Conditional rendering is essential for managing dynamic, state-driven interfaces:
- Loading States: Displaying a loading spinner while data is being fetched from an API, and rendering the actual content once it arrives.
- Authentication Controls: Showing a "Log In" button for guest users, and rendering a user menu or dashboard for authenticated users.
- Alert Overlays: Rendering dialog warnings, notification badges, or success popups only when specific conditions are met.
4. Real-World Analogy
Think of React conditional rendering like **a store sign outside a shop**:
- Open Sign: If the store is open (state: Open), render the illuminated neon sign displaying "WE ARE OPEN".
- Closed Sign: If the store is closed (state: Closed), render the dark sign displaying "SORRY, WE ARE CLOSED". The store uses a condition (open status) to determine which sign is displayed outside. Conditional rendering uses the same logic to display different layout elements.
5. Core Concepts
Below is a comparison of Ternary operators and Logical AND shortcuts in JSX:
| Feature | Ternary Operator (? :) |
Logical AND (&&) |
|---|---|---|
| Layout Output | Returns Element A if true; returns Element B if false. | Returns Element A if true; renders nothing if false. |
| Standard Use Case | Alternating views (e.g. Log In vs Log Out buttons). | Optional indicators (e.g. rendering a notification badge only if unread count exists). |
| Boilerplate Level | Medium; requires defining both branches. | Low; only requires the truthy branch. |
6. Syntax & API Reference
This example shows different conditional rendering patterns in React:
7. Visual Diagram
This diagram displays the conditional branch logic during render cycles:
8. Live Example — Full Working Code
Below is a complete, single-file HTML page showing loading states and conditional lists:
What just happened? If isLoading is true, the component immediately returns a simple "Authenticating..." loading panel, bypassing the main layout. When isLoading is false, React uses the ternary operator (isLoggedIn ? UserPanel : LoginPanel) to render the correct view based on the isLoggedIn state.
9. Interactive Playground
Try It Yourself Challenges:
- Add a new boolean state named
hasError. If true, display a red error message at the top of the main container using the logical AND (&&) operator. - Modify the simulated login timeout duration to verify how the loading screen interacts with state updates.
10. Common Mistakes
| Mistake | Why it happens | Wrong | Correct |
|---|---|---|---|
| Rendering numeric 0 when using the logical AND shortcut | If the left-hand side of a logical && expression evaluates to 0, JavaScript returns 0 directly. React then renders this number in the DOM. |
{list.length && <List />} (renders "0" if list is empty) |
{list.length > 0 && <List />} (left-hand side evaluates to boolean false, rendering nothing) |
| Writing if/else statements directly inside JSX blocks | JSX only accepts JavaScript expressions that evaluate to a value. Standard if statements do not return values directly, resulting in syntax errors. |
return ( |
Use a ternary operator inside the JSX block, or move the if/else statement outside the return block. |
11. Best Practices
- Keep JSX clean: If your ternary operator gets complex, move the conditional logic outside the return block, or break the code down into smaller child components.
- Use boolean values with `&&`: Always ensure the left-hand side of a logical `&&` operator evaluates to a boolean (e.g. `list.length > 0 && ...`) to prevent number leakage (like rendering `0` when empty).
- Return null to hide components: If a component should not render anything, return `null` explicitly rather than returning empty fragment elements (`<>`).
12. Browser Compatibility/Requirements
Conditional rendering uses standard JavaScript logic and operators, which are supported in all web browsers.
13. Interview Questions
Q1: How do you prevent a component from rendering anything in React?
Answer: A component can prevent itself from rendering by returning null (or an empty array/fragment) from its return block. This tells React to skip rendering the component without throwing errors or leaving placeholder nodes in the DOM.
Q2: Why does writing `{items.length && }` sometimes display "0" on the screen when the array is empty?
Answer: The logical AND (&&) operator returns the value of the left-hand side if it is falsy. When items.length is 0, JavaScript evaluates the expression to 0. Since 0 is a valid number, React renders it on the screen. To fix this, change the condition to evaluate to a boolean, such as `items.length > 0 && `.
14. Debugging Exercise
Identify the compile-time syntax error in this conditional rendering block:
Diagnosis: The ternary operator (? :) requires both the truthy and falsy branches to be defined. Omitting the falsy branch results in a syntax error.
Fix: Return null inside the falsy branch, or use a logical AND (&&) operator instead:
15. Practice Exercises
Exercise 1: Create a system connection status widget
Build a component named ConnectionStatus that accepts a status string prop (e.g. `'online'`, `'offline'`, `'connecting'`). Render a matching indicator badge using a switch statement or a lookup table.
16. Scenario-Based Challenge
The Dynamic Premium Feature Lock:
You are designing a page containing locked premium features. Free users should see a lock overlay with a call-to-action button, while premium users should see the actual feature. Describe how you would implement this using conditional rendering and how you would structure the parent component layout to prevent data leakage.
17. Quick Quiz
Q1: What does a component render if it returns null?
A) An empty paragraph tag: <p></p>
B) Absolutely nothing (no DOM nodes are created)
C) An error message on the screen
Answer: B — Returning null tells React to render nothing, preventing any DOM nodes from being created.
18. Summary & Key Takeaways
- Conditional rendering allows components to display different UI structures based on state or props.
- Use standard
if/elsestatements outside the returned JSX block. - Use the ternary operator (
? :) for inline conditions that have two branches. - Use the logical AND (
&&) operator for inline conditions that only have a truthy branch.
19. Cheat Sheet
| Conditional Pattern | Syntax Example |
|---|---|
| Ternary (Two branches) | {cond ? <A /> : <B />} |
| Logical AND (Truthy only) | {cond && <A />} |
| Prevent rendering | if (!show) return null; |