Conditional Rendering
How to render different UI elements depending on state or props using JavaScript.
What it is
Conditional rendering in React works exactly the same way conditions work in JavaScript.
Because React components are just functions, you can use standard JavaScript like if statements, ternary operators (? :), and logical AND (&&) to return different JSX depending on the current state.
Why it matters
Almost every application requires dynamic UI. You need to show a 'Login' button for guests, but a 'Profile' picture for authenticated users. You need to show a spinner while data loads, and a list when it's done.
React doesn't invent new template languages for this (like ng-if or v-if). It relies purely on native JavaScript.
The three main approaches
**1. Early Return:** Use a standard if statement *before* your final return to exit the component entirely: if (isLoading) return <Spinner />;
**2. Ternary Operator:** Use this inside JSX when you need to choose between two elements: {isLoggedIn ? <Admin /> : <Guest />}
**3. Logical AND:** Use this inside JSX when you want to render something OR nothing: {unreadMessages > 0 && <Badge />}
The Three Techniques
Toggle the Admin switch to see how all three JavaScript conditional techniques update the UI simultaneously.
Toggle the switch. Notice how the Early Return, Logical AND, and Ternary Operator all react differently based on the exact same boolean state.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Use
ifstatements for early returns to replace the entire component output. - Use ternary operators (
? :) inside JSX to choose between two options. - Use logical AND (
&&) inside JSX to render something conditionally or nothing at all. - Be careful with numbers on the left side of
&&—convert them to booleans to avoid rendering a0.
Done with this concept?
Mark it complete to track your progress. No login needed.