Lesson 23 of 60 – Conditional Rendering
38%

Conditional Rendering

Conditional rendering means displaying different content or components depending on a condition. React uses normal JavaScript conditions such as if, the ternary operator ?:, and the logical AND operator && to decide what should appear on the screen.

Note: Conditional rendering is commonly used for login status, loading messages, error messages, permissions, empty lists, and showing or hiding UI elements.

1. What is Conditional Rendering?

Conditional rendering means rendering different JSX based on a condition.

function App() {

    const isLoggedIn = true;

    if (isLoggedIn) {
        return <h2>Welcome Back!</h2>;
    }

    return <h2>Please Login</h2>;

}

2. Why Use Conditional Rendering?

Conditional rendering helps an application display appropriate content based on the current situation.

  • Show Login or Logout buttons.
  • Display loading messages.
  • Show error messages.
  • Display user-specific content.
  • Show empty-state messages.
  • Control access to parts of an interface.
  • Display different UI based on state.

3. Using an if Statement

A normal JavaScript if statement can be used before the JSX is returned.

function Greeting() {

    const isMorning = true;

    if (isMorning) {
        return <h2>Good Morning</h2>;
    }

    return <h2>Good Evening</h2>;

}

4. if and else

The if...else statement can display one of two different results.

function UserStatus() {

    const loggedIn = true;

    if (loggedIn) {

        return <h2>Welcome User</h2>;

    } else {

        return <h2>Please Login</h2>;

    }

}

5. Conditional Rendering with Props

Props can be used as conditions.

function UserStatus({ loggedIn }) {

    if (loggedIn) {

        return <h2>
            Welcome Back!
        </h2>;

    }

    return <h2>
        Please Login
    </h2>;

}
<UserStatus loggedIn={true} />

6. Conditional Rendering with State

State can also control which content is displayed.

import { useState } from "react";

function App() {

    const [loggedIn, setLoggedIn] = useState(false);

    if (loggedIn) {

        return <h2>
            Welcome!
        </h2>;

    }

    return <h2>
        Please Login
    </h2>;

}

7. Ternary Operator

The ternary operator is useful when you need to choose between two values or JSX elements.

The syntax is:

condition ? valueIfTrue : valueIfFalse
function App() {

    const loggedIn = true;

    return (
        <h2>
            {loggedIn
                ? "Welcome"
                : "Please Login"
            }
        </h2>
    );

}

8. Ternary with JSX

The ternary operator can return complete JSX elements.

function App() {

    const loggedIn = true;

    return (
        <div>

            {loggedIn ? (
                <h2>
                    Welcome Back!
                </h2>
            ) : (
                <button>
                    Login
                </button>
            )}

        </div>
    );

}

9. Logical AND Operator

The logical AND operator && can be used when something should be rendered only if a condition is true.

function App() {

    const isAdmin = true;

    return (
        <div>

            {isAdmin && (
                <button>
                    Admin Panel
                </button>
            )}

        </div>
    );

}

10. Showing a Message Conditionally

function App() {

    const isAvailable = true;

    return (
        <div>

            <h2>
                Product
            </h2>

            {isAvailable && (
                <p>
                    Product is available.
                </p>
            )}

        </div>
    );

}

11. Login and Logout Example

function User({ loggedIn }) {

    return (
        <div>

            {loggedIn ? (
                <button>
                    Logout
                </button>
            ) : (
                <button>
                    Login
                </button>
            )}

        </div>
    );

}

12. Loading State

Conditional rendering is commonly used while data is loading.

function App({ loading }) {

    if (loading) {

        return <h2>
            Loading...
        </h2>;

    }

    return <h2>
        Data Loaded
    </h2>;

}

13. Error Message

An error message can be displayed when an error condition is true.

function Status({ error }) {

    return (
        <div>

            {error && (
                <p>
                    Something went wrong.
                </p>
            )}

        </div>
    );

}

14. Empty List Message

You can display a message when an array contains no items.

function StudentList({ students }) {

    if (students.length === 0) {

        return <p>
            No students found.
        </p>;

    }

    return (
        <ul>

            {students.map(student => (
                <li key={student.id}>
                    {student.name}
                </li>
            ))}

        </ul>
    );

}

15. Conditional Rendering with Comparison

Conditions can use comparison operators.

function Result({ marks }) {

    return (
        <div>

            {marks >= 40 ? (
                <h2>
                    Passed
                </h2>
            ) : (
                <h2>
                    Failed
                </h2>
            )}

        </div>
    );

}

16. Multiple Conditions

Multiple conditions can be handled using if...else if...else.

function Grade({ marks }) {

    if (marks >= 80) {

        return <h2>
            Grade A
        </h2>;

    } else if (marks >= 60) {

        return <h2>
            Grade B
        </h2>;

    } else if (marks >= 40) {

        return <h2>
            Grade C
        </h2>;

    }

    return <h2>
        Fail
    </h2>;

}

17. Multiple Conditions with Ternary

Nested ternary operators are possible, but too many nested conditions can make code difficult to read.

function Grade({ marks }) {

    return (
        <h2>

            {marks >= 80
                ? "A"
                : marks >= 60
                    ? "B"
                    : marks >= 40
                        ? "C"
                        : "Fail"
            }

        </h2>
    );

}

18. Conditional CSS Class

Conditions can also be used to select a CSS class.

function Status({ active }) {

    return (
        <div
            className={
                active
                    ? "active"
                    : "inactive"
            }
        >
            User Status
        </div>
    );

}

19. Conditional Button

function Account({ loggedIn }) {

    return (
        <div>

            {loggedIn ? (
                <button>
                    Logout
                </button>
            ) : (
                <button>
                    Login
                </button>
            )}

        </div>
    );

}

20. Conditional Component Rendering

You can conditionally render complete React components.

function Dashboard() {
    return <h2>Dashboard</h2>;
}

function Login() {
    return <h2>Login Page</h2>;
}

function App({ loggedIn }) {

    return (
        <div>

            {loggedIn
                ? <Dashboard />
                : <Login />
            }

        </div>
    );

}

21. Conditional Rendering with State

import { useState } from "react";

function App() {

    const [show, setShow] = useState(false);

    return (
        <div>

            <button
                onClick={() => setShow(!show)}
            >
                Toggle
            </button>

            {show && (
                <p>
                    This content is visible.
                </p>
            )}

        </div>
    );

}

22. Toggle Content

The previous example can be used to show or hide content.

function App() {

    const [show, setShow] = useState(false);

    return (
        <div>

            <button
                onClick={() => setShow(!show)}
            >
                {show ? "Hide" : "Show"}
            </button>

            {show && (
                <div>
                    <h3>
                        More Information
                    </h3>

                    <p>
                        Welcome to React.
                    </p>
                </div>
            )}

        </div>
    );

}

23. Conditional Rendering with Boolean Values

Boolean values are frequently used for conditional rendering.

function AdminPanel({ isAdmin }) {

    return (
        <div>

            {isAdmin && (
                <button>
                    Admin Dashboard
                </button>
            )}

        </div>
    );

}

24. Conditional Rendering with Null

A component can return null when it should render nothing.

function Warning({ show }) {

    if (!show) {

        return null;

    }

    return (
        <div>
            Warning: Check your input.
        </div>
    );

}

When show is false, the component renders nothing.

25. Conditional Rendering in Lists

Conditions can be used while rendering items from an array.

function Students({ students }) {

    return (
        <ul>

            {students.map(student => (
                student.active && (
                    <li key={student.id}>
                        {student.name}
                    </li>
                )
            ))}

        </ul>
    );

}

26. Conditional Rendering for User Roles

Different content can be shown based on a user's role.

function Dashboard({ role }) {

    if (role === "admin") {

        return <h2>
            Admin Dashboard
        </h2>;

    }

    if (role === "teacher") {

        return <h2>
            Teacher Dashboard
        </h2>;

    }

    return <h2>
        Student Dashboard
    </h2>;

}

27. Loading, Error and Data States

A common application pattern is to handle loading, error, and successful data states separately.

function DataView({
    loading,
    error,
    data
}) {

    if (loading) {

        return <p>
            Loading...
        </p>;

    }

    if (error) {

        return <p>
            Failed to load data.
        </p>;

    }

    return (
        <div>
            {data}
        </div>
    );

}

28. Common Conditional Rendering Mistakes

  • Using an incorrect condition.
  • Forgetting the alternative part of a ternary expression.
  • Creating deeply nested ternary expressions.
  • Calling functions unnecessarily during rendering.
  • Using unclear boolean variable names.
  • Forgetting to handle loading or error states.
  • Rendering content when the required data is missing.
  • Using complicated conditions directly inside JSX.

29. Complete Conditional Rendering Example

import { useState } from "react";

function App() {

    const [loggedIn, setLoggedIn] = useState(false);

    return (
        <div>

            <h1>
                Student Portal
            </h1>

            {loggedIn ? (
                <div>

                    <h2>
                        Welcome Student
                    </h2>

                    <button
                        onClick={() =>
                            setLoggedIn(false)
                        }
                    >
                        Logout
                    </button>

                </div>
            ) : (
                <div>

                    <h2>
                        Please Login
                    </h2>

                    <button
                        onClick={() =>
                            setLoggedIn(true)
                        }
                    >
                        Login
                    </button>

                </div>
            )}

        </div>
    );

}

export default App;

This example uses state and the ternary operator to display different content based on the login status.

30. Conditional Rendering Best Practices

  • Use if statements for larger conditional logic.
  • Use the ternary operator for simple two-way choices.
  • Use && when content should appear only when a condition is true.
  • Keep complex conditions outside JSX when possible.
  • Use meaningful boolean variable names.
  • Handle loading, error, and empty states clearly.
  • Avoid deeply nested ternary operators.
  • Use reusable components for complicated conditional interfaces.
  • Return null when a component should render nothing.
  • Keep conditional rendering easy to read and understand.

📌 Key Points

  • Conditional rendering displays different UI based on conditions.
  • React uses normal JavaScript conditions for rendering.
  • if...else can be used before returning JSX.
  • The ternary operator is useful for two different UI choices.
  • && can conditionally display content.
  • Props and state can control conditional rendering.
  • Complete components can be conditionally rendered.
  • Loading, error, empty, and success states can be handled conditionally.
  • A component can return null to render nothing.
  • Clear conditions make React applications easier to maintain.

🧠 Quick Quiz

Question: Which JavaScript operator is commonly used in React to conditionally render something only when a condition is true?