</>
Skip to content
React lessons (13/47)

React — Conditional Rendering

If/Else with Ternary

function Greeting({ isLoggedIn }) {
    return (
        <div>
            {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
        </div>
    );
}

If/Else with &&

function Mailbox({ unreadMessages }) {
    return (
        <div>
            <h1>Hello!</h1>
            {unreadMessages.length > 0 &&
                <h2>You have {unreadMessages.length} unread messages.</h2>
            }
        </div>
    );
}

Prevent Rendering

function WarningBanner({ warn }) {
    if (!warn) {
        return null; // Don't render anything
    }

    return <div className="warning">Warning!</div>;
}

Conditional Classes

function TodoItem({ todo }) {
    return (
        <li className={todo.completed ? 'completed' : ''}>
            {todo.text}
        </li>
    );
}

Conditional Examples

// Login status
function LoginStatus({ isLoggedIn, username }) {
    if (isLoggedIn) {
        return (
            <div>
                <p>Welcome, {username}!</p>
                <button>Logout</button>
            </div>
        );
    }

    return (
        <div>
            <p>Please log in</p>
            <button>Login</button>
        </div>
    );
}

// Loading state
function DataLoader({ isLoading, data }) {
    if (isLoading) {
        return <div>Loading...</div>;
    }

    if (!data) {
        return <div>No data available</div>;
    }

    return (
        <div>
            <h2>Data:</h2>
            <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
    );
}

// Permission check
function AdminPanel({ user }) {
    if (user.role !== 'admin') {
        return <div>Access denied</div>;
    }

    return (
        <div>
            <h2>Admin Panel</h2>
            <p>Welcome, Admin!</p>
        </div>
    );
}

Mini Practice

Write React code that:

  1. Uses ternary operator for conditional rendering
  2. Uses && for conditional rendering
  3. Returns null for no rendering
  4. Applies conditional classes

Up Next

Next: Learn about Rendering Lists.

Related Topics

Frequently Asked Questions about Conditional Rendering

What is Conditional Rendering in React?

Conditional Rendering is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Conditional Rendering?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Conditional Rendering.

Why is Conditional Rendering important in React?

Conditional Rendering is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.