Conditional Rendering

How to render different UI elements depending on state or props using JavaScript.

React3 min readConcept 11 of 46

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.

function AdminBadge({ isAdmin }) {
// 1. Early Return (replaces entire output)
if (!isAdmin) return null;
return Admin;
}
 
export default function Profile({ isAdmin }) {
return (
<AdminBadge isAdmin={isAdmin} />
 
{/* 2. Logical AND (render or nothing) */}
{isAdmin && }
 
{/* 3. Ternary (choose between two) */}
{isAdmin ? : }
);
}

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.

  1. 1Why can't you write an `if` statement directly inside JSX, like `<div>{if (user) { return <Avatar /> }}</div>`?
  2. 2What will render if you write `<div>{count && <Counter />}</div>` and `count` is `0`?
  3. 3Which operator is best for showing either a Login button or a Logout button depending on state, directly inside your JSX?

Remember this

  • Use if statements 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 a 0.

Done with this concept?

Mark it complete to track your progress. No login needed.