React Fundamentals

Learn React from scratch including components, JSX, props, and state basics.

beginner Frontend Frameworks 5 hours

Chapter 8: Conditional Rendering

Chapter 8 of 15

Chapter 8: Conditional Rendering

8.1 Conditional Rendering Methods

Conditional rendering displays different UI based on conditions. React supports multiple approaches.

Ternary Operator:

function App() {
    const isLoggedIn = true;
    
    return (
        <div>
            {isLoggedIn ? <Welcome /> : <Login />}
        </div>
    );
}

If-Else Statements:

function App() {
    const isLoggedIn = true;
    
    if (isLoggedIn) {
        return <Welcome />;
    } else {
        return <Login />;
    }
}

Early Return:

function UserProfile({ user }) {
    if (!user) {
        return <div>Loading...</div>;
    }
    
    return (
        <div>
            <h1>{user.name}</h1>
            <p>{user.email}</p>
        </div>
    );
}

8.2 Logical && Operator

Use && operator for simple conditional rendering.

function App() {
    const isLoading = true;
    const hasError = false;
    
    return (
        <div>
            {isLoading && <Spinner />}
            {hasError && <ErrorMessage />}
            {!isLoading && !hasError && <Content />}
        </div>
    );
}

Common Patterns:

// Show/hide based on condition
{isVisible && <Component />}

// Multiple conditions
{user && user.isAdmin && <AdminPanel />}

// Conditional classes
<div className={isActive ? 'active' : 'inactive'}>

// Conditional attributes
<button disabled={!isValid}>Submit</button>

8.3 Switch Statements

Use switch statements for multiple conditions.

function StatusMessage({ status }) {
    switch (status) {
        case 'loading':
            return <Spinner />;
        case 'success':
            return <SuccessMessage />;
        case 'error':
            return <ErrorMessage />;
        default:
            return null;
    }
}

8.4 Conditional Rendering Best Practices

Follow best practices for clean conditional rendering.

  • Keep conditions simple and readable
  • Extract complex conditions to variables
  • Use early returns for clarity
  • Avoid deeply nested ternaries
  • Consider extracting to separate components